<aside> 💡
진행 순서
extra. 인메모리 사용법
</aside>
Member라는 가상의 엔티티가 존재하고, email이 식별자인 경우이다.
POST /login 요청을 보냄UsernamePasswordAuthenticationFilter(기본?)**가 요청을 가로챔DaoAuthenticationProvider가 UserDetailsService를 이용해 사용자 인증 수행defaultSuccessUrl("/")으로 이동 implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/login", "/resources/**").permitAll()
.anyRequest().authenticated() // 그외 모든 곳은 인
)
.formLogin(login -> login
.loginPage("/login") // 커스텀 로그인 페이지
.defaultSuccessUrl("/home", true) // 로그인 성공시 url
.permitAll()
)
.csrf(csrf -> csrf.disable()) // CSRF 보호 비활성화
.logout(logout -> logout
.logoutUrl("/logout") // 로그아웃 엔트포인트
.logoutSuccessUrl("/login?logout") // 로그아웃 성공시 url
.invalidateHttpSession(true) // 세션 무효화
.deleteCookies("JSESSIONID") // 쿠키 삭제
.permitAll()
)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS) // 기본 세션 설정
);
return http.build();
}
}
시큐리티 설정 Configuration 클래스는 @EnableWebSecurity가 반드시 필요하다.
authorizeHttpRequest설정, 인증, 인가 요청 정책 정의, 접근 제어, url과 매치시킨다. 적용순서는 상단부터 FilterSecurityInterceptor를 구성한다.
hasAnyRole : 롤 여러가지 설정hasRole : 특정한 롤이 있어여 경로 접근허용permitAll : 모든사용자 허용authenticated : 로그인만 하면 접근 허용denyAll : 모든 사용자 접근 거부anonymousformLogin으로 커스텀 login 페이지를 등록한다. 로그인 성공시에 defualtSucessUrl에서 설정한 페이지로 이동한다.
.formLogin(login -> login
.loginPage("/login")
.defaultSuccessUrl("/home", false) // 이전 페이지가 있으면 그대로, 없으면 "/home"으로 이동
)
커스텀 핸들러 사용
.formLogin(login -> login
.loginPage("/login")
.successHandler((request, response, authentication) -> {
response.sendRedirect("/custom-success"); // 로그인 성공 후 특정 URL로 이동
})
)
logout 설정으로, 로그아웃과 로그아웃 후 url 설정
sessionManagement으로 세션 생성 정책 설정
SessionCreationPolicy.ALWAYS :
SessionCreationPolicy.IF_REQUIRED :
SessionCreationPolicy.NEVER :
SessionCreationPolicy.STATELESS :