Published 2023. 1. 7. 01:58
반응형
- [Spring Boot] Spring Security를 사용한 로그인 구현 (Form Login) 여기서 Spring Security를 사용한 로그인을 구현했었음
- 인증, 인가 실패 시 Spring Security에서 정해진 방식대로 처리했었음
- 인증 실패 시 401 에러 출력 or 로그인 페이지로 redirect
- 인가 실패 시 403 에러 출력
- 인증, 인가 실패 시 내가 원하는 방식으로 처리하고 싶다면 authenticationEntryPoint(인증 실패), accessDeniedHandler(인가 실패)를 사용하면 됨
authenticationEntryPoint, accessDeniedHandler 사용 예제
SecurityConfig
- 전에 작성한 SecurityConfig의 configure(HttpSecurity http) 메서드에 아래의 코드 추가
http
.exceptionHandling()
.authenticationEntryPoint(new MyAuthenticationEntryPoint())
.accessDeniedHandler(new MyAccessDeniedHandler());
- 인증에 실패(로그인 하지 않은 경우)하면 MyAuthenticationEntryPoint 호출
- 인가에 실패(권한이 없는 경우)하면 MyAccessDeniedHandler 호출
MyAuthenticationEntryPoint
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.sendRedirect("/authentication-fail");
}
}
- 인증에 실패 시 /authentication-fail URL로 redirect
- Controller에서 해당 URL과 인증 실패시 출력될 html을 매핑
MyAccessDeniedHandler
public class MyAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.sendRedirect("/authorization-fail");
}
}
- 인가에 실패 시 /authorization-fail URL로 redirect
- Controller에서 해당 URL과 인가 실패시 출력될 html을 매핑
결과
- 인증 실패 처리 전 (로그인 페이지로 redirect)
- 인증 실패 처리 후 (인증 실패 출력 페이지로 redirect)
- 인가 실패 처리 전 (403 에러 출력 페이지)
- 인가 실패 처리 후 (인증 실패 출력 페이지로 redirect)
추가 - 클래스를 따로 만들지 않고 아래와 같이 익명 클래스로 구현하는 것도 가능
http
.exceptionHandling()
.authenticationEntryPoint(new AuthenticationEntryPoint() {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.sendRedirect("/security-login/authentication-fail");
}
})
.accessDeniedHandler(new AccessDeniedHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.sendRedirect("/security-login/authorization-fail");
}
});
반응형
'Spring Boot > 문법 정리' 카테고리의 다른 글
[Spring Boot] Front-End 없이 Jwt 화면 로그인 구현 (1) | 2023.01.07 |
---|---|
[Spring Boot] Spring Security를 사용한 Jwt Token 로그인 구현 (1) | 2023.01.07 |
[Spring Boot] Spring Security를 사용한 로그인 구현 (Form Login) (1) | 2023.01.06 |
[Spring Boot] Session을 사용한 로그인 구현 (7) | 2023.01.04 |
[Spring Boot] Cookie를 사용한 로그인 구현 (1) | 2023.01.02 |