본문 바로가기
개발/Security

[SpringBoot] Security + JWT(Access , Refresh) - Handler

by 코딩하는 흰둥이 2024. 9. 25.

이전글

https://greed-yb.tistory.com/290

 

[SpringBoot] Security + JWT(Access , Refresh) - JwtAuthenticationFilter

이전글https://greed-yb.tistory.com/289 [SpringBoot] Security + JWT(Access , Refresh) - JwtTokenUtil이전글https://greed-yb.tistory.com/288 [SpringBoot] Security + JWT(Access , Refresh) - SecurityConfig권한에 따른 인증/인가 방식은 이전

greed-yb.tistory.com

 

 

 

 

Security Config 에 설정하는 Exception Handler

 

WebAccessDeniedHandler.class
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;

public class WebAccessDeniedHandler implements AccessDeniedHandler {

    private String errorPage = "/denied";

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        String deniedUrl = errorPage + "?exception=" + accessDeniedException.getMessage();
        response.sendRedirect(deniedUrl);
    }
}

 

 

WebAuthenticationEntryPoint.class
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

public class WebAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {

        // 인증되지 않은 사용자는 login 페이지로 이동
        if (authException != null && authException.getCause() instanceof InsufficientAuthenticationException) {
            response.sendRedirect("/login");
        } else {
            // 인증 오류의 경우 401
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
        }
    }
}

 

 

권한이 없는 경우 WebAccessDeniedHandler

Token 이 만료되었거나 유효하지 않는 경우 WebAuthenticationEntryPoint 

댓글