Spring Security 구조
AccessDeniedHandler
Spring Security 적용
@Configuration
@AllArgsConstructor
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig {
private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
private final CustomAccessDeniedHandler customAccessDeniedHandler;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.
...
.and().exceptionHandling()
.authenticationEntryPoint(customAuthenticationEntryPoint)
.accessDeniedHandler(customAccessDeniedHandler);
return http.build();
}
@Bean
public AccessDeniedHandler accessDeniedHandler() {
CustomAccessDeniedHandler accessDeniedHandler = new CustomAccessDeniedHandler();
accessDeniedHandler.setErrorURL("/auth/denied");
return accessDeniedHandler;
}
}
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Setter
private String errorURL;
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
String deniedUrl = errorURL + "?message=" + accessDeniedException.getMessage();
response.sendRedirect(deniedUrl);
}
}
@Controller
@RequestMapping("/auth")
@RequiredArgsConstructor
public class SecurityController {
@GetMapping("/denied")
public ResponseEntity failedSecure(@RequestParam String message){
return new ResponseEntity(
new Response(403, message), HttpStatus.NOT_ACCEPTABLE
);
}
}
Spring Security 구조 일부
AuthenticationEntryPoint
Spring Secutiry 적용
@Configuration
@AllArgsConstructor
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig {
private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
private final CustomAccessDeniedHandler customAccessDeniedHandler;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.
...
.and().exceptionHandling()
.authenticationEntryPoint(customAuthenticationEntryPoint)
.accessDeniedHandler(customAccessDeniedHandler);
return http.build();
}
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
throws IOException, ServletException {
response.sendRedirect("/auth/not-secured");
}
}
@Controller
@RequestMapping("/auth")
@RequiredArgsConstructor
public class SecurityController {
@GetMapping("/not-secured")
public ResponseEntity notSecured(){
return new ResponseEntity(
new Response(401, "로그인이 되지 않았습니다."), HttpStatus.UNAUTHORIZED
); // 권한이 여러개일 경우에는 따로 설정해주어야 한다.
}
}