Spring 37

[스프링 시큐리티] 스프링 시큐리티 테스트 - RequestPostProcessor, Annotations

기존의 불편한 수동테스트 직접 파라미터를 통한 가입 - 로그인 - 조회로 테스트 반복되는 수동 단위 테스트에 불필요한 시간 소모가 큼 pom.xml org.springframework.security spring-security-test test ${spring-security.version} spring-security version을 따라가게끔 설정 SecurityMockMvcRequestPostProcessors를 이용한 테스트 방법 @ExtendWith(SpringExtension.class) @SpringBootTest @AutoConfigureMockMvc public class AccountControllerTest { @Autowired MockMvc mockMvc; @Test public..

스터디-Spring 2022.01.09

[스프링 시큐리티] 스프링 시큐리티 커스터마이징 - PasswordEncoder

스프링 시큐리티의 비밀번호는 반드시 인코딩 해야한다 스프링 시큐리티가 제공하는 PasswordEncoder는 특정한 포맷으로 동작함 {id}EncodedPassword 다양한 전략의 패스워드 인코더를 사용할 수 있다. @Bean public PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } 위와 같이 Bean을 등록하면 스프링 시큐리티가 기본적으로 제공하는 다양한 인코더를 사용할 수 있다 public final class PasswordEncoderFactories { private PasswordEncoderFactories() { } public static Pas..

스터디-Spring 2022.01.08

[스프링 시큐리티] 스프링 시큐리티 커스터마이징 - JPA 연동

JPA + H2 추가 org.springframework.boot spring-boot-starter-data-jpa com.h2database h2 runtime Account Entity @Entity public class Account { @Id @GeneratedValue private Integer id; @Column(unique = true) private String username; private String password; private String role; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return use..

스터디-Spring 2022.01.07

[스프링 시큐리티] 스프링 시큐리티 커스터마이징 - 인메모리 유저 추가

자동 설정 유저 정보는 UserDetailsServiceAutoConfiguration SecurityProperties 위의 클래스를 통해서 설정 된다. Properties에서 유저정보 설정하기 application.properties spring.security.user.name=admin spring.security.user.password=123 spring.security.user.roles=ADMIN 위와 같이 설정하면 어플리케이션 시작시 자동 설정되던 유저는 사라지고 위의 정보로 세팅된다. roles도 설정되었기 때문에 /admin 페이지도 접근 가능하다 SecurityConfig에 설정하기 @Configuration @EnableWebSecurity public class SecurityC..

스터디-Spring 2022.01.07

[스프링 시큐리티] 스프링 시큐리티 설정하기

스프링 웹 시큐리티 설정 추가 @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .mvcMatchers("/", "/info").permitAll() .mvcMatchers("/admin").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); } } authorizeRequest() -어떻게 요청들을..

스터디-Spring 2022.01.07

[스프링 시큐리티] 스프링 시큐리티 연동

스프링 시큐리티 의존성 설정 pom.xml org.springframework.boot spring-boot-starter-security 스프링 시큐리티가 제공하는 자동 설정이 적용된다. 적용 전의 문제 인증할 방법이 없었다 현재 사용자가 누군지 알 수가 없다 자동 설정( 스프링 시큐리티 의존성을 추가하게 되면) 모든 요청은 인증을 필요로 한다 - 위와 같은 로그인 폼으로 리다이렉트 기본 유저가 생성된다 username: user password: 로그 확인 @GetMapping("/") public String index(Model model, Principal principal) { if (principal == null) { model.addAttribute("message", "Hello Spr..

스터디-Spring 2022.01.07

[스프링 핵심 원리 - 기본편] 컴포넌트 스캔과 자동 의존관계 설정

스프링 빈을 등록하는 2가지 방법 1. 컴포넌트 스캔과 자동 의존관계 설정 2. 자바 코드로 직접 스프링 빈 등록하기 컴포넌트 스캔과 자동 의존관계 설정 1. @Component애노테이션이 있으면 스프링 빈으로 자동 등록된다. 2. @Controller 컨트롤러가 스프링 빈으로 자동 등록된 이유도 컴포넌트 스캔 때문이다. 3. @Component를 포함하는 다음 애노테이션도 스프링 빈으로 자동 등록된다. - @Controller, @Service, @Repository 4. @ComponentScan 애노테이션이 붙은 클래스 기준으로 스캔을 하는데 동일패키지를 포함한 하위 패키지를 스캔하며, 상위패키지나 다른 패키지는 스캔하지 못한다(설정에 따라 달라짐) ※ 스프링은 스프링 컨테이너에 스프링 빈을 등록할..

스터디-Spring 2022.01.03

[스프링 핵심 원리 - 기본편] 스프링이란?

스프링 생태계 1. 스프링 프레임워크 핵심기술 : DI 컨테이너, AOP. 이벤트 등 웹 기술: MVC, WebFlux 등 데이터 접근 기술: JDBC ORM 등 을 아우르는 프레임워크 2. 스프링 부트 스프링을 편리하게 사용할 수 있도록 지원, 최근에는 기본으로 사용 단독으로 실행할 수 있는 스프링 애플리케이션을 쉽게 생성, 내장 Tomcat 지원으로 웹서버를 별도로 설치하지 않아도 됨 Spring starter로 손쉬운 빌드 구성 가능 메트릭, 상태 확인, 외부 구성 같은 프로덕션 준비 가능 ( 운영 모니터링 등) 관례에 의한 간결한 설정 스프링이라는 단어란 무엇인가 - 스프링 DI 컨테이너 기술 - 스프링 프레임워크, 스프링 부트 모두를 포함한 생태계 스프링은 왜 만들었을까?( 핵심 개념 ) 객체 ..

스터디-Spring 2021.12.28

Thymeleaf - 표준 표현식

${...} : Variable expressions - OGNL 표현식, 스프링환경에서는 Spring EL ${shop.product.name} *{...} : Selection expressions - 변수 표현식과 동일하지만, 전체 컨텍스트 맵이 아닌 이전에 선택한 객체가 기준이됨 *{product.name} ... ... ... #{...} : Message (i18n) expressions - .properties 같은 파일에서 값을 읽어 표현 할 수 있다. Spring 환경에서는 MessageSource과 통합됨 (docs.spring.io/spring-framework/docs/4.3.30.RELEASE/spring-framework-reference/htmlsingle/#context-fu..

Spring 2021.01.27

SpringBoot Mysql Datasource 세팅

SpringBoot에서 Mysql Datasource 세팅하기. 필자는 JPA, Gradle로 진행했다.(Mybatis같은 환경도 아래 세팅으로 사용가능 할 듯) Gradle.build dependencies { ... implementation ("mysql:mysql-connector-java") implementation "org.springframework.boot:spring-boot-starter-data-jpa" ... } JPA 사용시에만 JPA 의존을 추가하자 DatabaseConfig.java @Slf4j @EnableJpaAuditing @Configuration public class DatabaseConfig { @Bean public PasswordEncoder passwordE..

Spring 2020.11.16