0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring Securityで未認証なのに403になる問題を解決する

0
Posted at

概要

Spring Securityの環境でAPIを叩くと、未認証のリクエストでも 403 Forbidden が返ります。

本来は401を返したいケースでも403になるため、そのままではステータスコードを正しく使い分けることができません。

原因

未認証時のレスポンスは AuthenticationEntryPoint によって決まります。

この設定を行っていない場合、未認証であっても401ではなく403が返る挙動になります。

解決方法

  1. AuthenticationEntryPoint を実装

    @Component
    public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    
      @Override
      public void commence(
        HttpServletRequest request,
        HttpServletResponse response,
        AuthenticationException authException
      ) throws IOException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      }
    }
    
  2. SecurityConfig に設定

    SecurityConfig.java
    .exceptionHandling(e -> e
      .authenticationEntryPoint(restAuthenticationEntryPoint)
    )
    

結果

  • 未認証 → 401
  • 認証済みだが権限不足 → 403

まとめ

Spring Securityでは、未認証時のレスポンスはAuthenticationEntryPointによって決まります。
これを明示的に設定することで、未認証(401)と認可エラー(403)を正しく分離できます。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?