올바른 값을 요청했으나 Spring Security 에선 403 에러가 발생합니다.
403에러를 해결해 봅시다.
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
return http
.formLogin(
formLogin -> formLogin
.loginPage("/login")
)
.formLogin(
loginFail -> loginFail
.failureHandler(failureHandler)
)
.oauth2Login(
oauth2Login -> oauth2Login
.loginPage("/member/login")
)
.logout(
logout -> logout
.logoutUrl("/member/logout")
.logoutSuccessUrl("/")
).build();
}
csrf를 비활성화 하는 방법입니다. 가장 원시적인 방법이라고 생각합니다.
실제로 이렇게 비활성화 한다면 잘 동작하는 것을 확인할 수 있습니다.
저는 배포환경과 개발환경을 분리했습니다.
개발 환경입니다.
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity(prePostEnabled = true)
@Profile("dev")
public class SecurityConfigDev {
private final FailureHandler failureHandler;
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
return http
.formLogin(
formLogin -> formLogin
.loginPage("/login")
)
.formLogin(
loginFail -> loginFail
.failureHandler(failureHandler)
)
.oauth2Login(
oauth2Login -> oauth2Login
.loginPage("/member/login")
)
.logout(
logout -> logout
.logoutUrl("/member/logout")
.logoutSuccessUrl("/")
).build();
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
배포 환경입니다.
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableMethodSecurity(prePostEnabled = true)
@Profile("prod")
public class SecurityConfig {
private final FailureHandler failureHandler;
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.formLogin(
formLogin -> formLogin
.loginPage("/login")
)
.formLogin(
loginFail -> loginFail
.failureHandler(failureHandler)
)
.oauth2Login(
oauth2Login -> oauth2Login
.loginPage("/member/login")
)
.logout(
logout -> logout
.logoutUrl("/member/logout")
.logoutSuccessUrl("/")
).build();
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@Component
class FailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
String encode = Ut.url.encode("권한이 없습니다.");
response.sendRedirect("?admin&error=true&msg=" + encode);
}
}