본문 바로가기

Spring

Security + OAUTH2 + H2 로그인 AccessDenied 경우 redirect되는 현상

수많은 시간과 수많은 질문들로도 답이 안나오던 이문제

드디어 해결했다.

 

https://okky.kr/article/732864

 

OKKY | OAuth2 권한 없으시 자동로그인 되는 문제 (redirect 해결방법을 여쭙고싶습니다.)

/boards 의 권한을 USER로 해놓았습니다. 로그인 전 상황에 /boards에 접근하면     -  Populated SecurityContextHolder with anonymous token   -  Access is denied (user is anonymous); redirecting to authentication entry p

okky.kr

질문은 위와같다.

 

나의 해결방법은

 

1.springconfig에 

  ㄴ http.exceptionHandling().authenticationEntryPoint(new CustomAuthenticationEntryPoint()) 

 

2.CustomAuthenticationEntryPoint 생성 


@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException
{ response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); }

}

을통해 세션이 없을경우 정상적인 401 에러 페이지를 송출해준다.