概要
Spring Securityの環境でAPIを叩くと、未認証のリクエストでも 403 Forbidden が返ります。
本来は401を返したいケースでも403になるため、そのままではステータスコードを正しく使い分けることができません。
原因
未認証時のレスポンスは AuthenticationEntryPoint によって決まります。
この設定を行っていない場合、未認証であっても401ではなく403が返る挙動になります。
解決方法
-
AuthenticationEntryPointを実装@Component public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence( HttpServletRequest request, HttpServletResponse response, AuthenticationException authException ) throws IOException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } -
SecurityConfigに設定SecurityConfig.java.exceptionHandling(e -> e .authenticationEntryPoint(restAuthenticationEntryPoint) )
結果
- 未認証 → 401
- 認証済みだが権限不足 → 403
まとめ
Spring Securityでは、未認証時のレスポンスはAuthenticationEntryPointによって決まります。
これを明示的に設定することで、未認証(401)と認可エラー(403)を正しく分離できます。