분류 전체보기 77

[스프링 시큐리티] AuthenticationManager와 Authentication

스프링 시큐리티에서 인증(Authentication)은 AuthenticationManager가 한다. Authentication authenticate(Authentication authentication) throws AuthenticationException; 파라미터인 Authentication이 유저가 입력한 id, pw 같은 인증정보를 가지고 있다 AuthenticationManager.authenticate를 통해 인증정보가 유효하다면 Principal를 담고있는 Authentication 객체를 리턴한다 계정이 비활성화 되어있다면 - DisabledException 계정이 잠겨있다면 - LockedException 인증정보가 잘못되었다면 - BadCredentialsException 기본적..

스터디-Spring 2022.01.10

[스프링 시큐리티] 스프링 시큐리티 테스트 - Form Login

폼 로그인 / 로그아웃 테스트 (SecurityMockMvcRequestBuilders) perform(formLogin()) perform(formLogin().user("admin").password("123")) perform(logout()) @Test @Transactional public void login_success() throws Exception { String username = "twlee"; String password = "123"; Account user = createUser(username, password); mockMvc.perform(formLogin().user(user.getUsername()).password(password)) .andExpect(authent..

스터디-Spring 2022.01.09

[스프링 시큐리티] 스프링 시큐리티 테스트 - 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