簡體   English   中英

如何使用 JWT 身份驗證處理 API REST 身份驗證異常?

[英]How to handle authentication exceptions on API REST with JWT authentication?

我實現了一個API REST使用Spring 安全Z1D1FADBD9150349C135781140FFEE9

一切正常,除非嘗試處理身份驗證提供程序拋出的異常。

這是我的安全配置 function:

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http
    .csrf().disable().formLogin().disable()
    .httpBasic().disable().logout().disable() 
    .sessionManagement().sessionCreationPolicy(STATELESS)
    .and().authorizeRequests().requestMatchers(PROTECTED_URLS).authenticated()
    .and().authenticationProvider(tokenAuthenticationProvider)
        .addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}

如您所見,我正在使用自定義提供程序和過濾器,以便使用我實現的 JWT 服務(使用io.jsonwebtoken ,所以不要擔心安全漏洞)。

我正在使用ResponseEntityExceptionHandler處理大多數異常。 但是這個處理程序不會捕獲 Provider 上拋出的異常。

所以,我嘗試實現一個AuthenticationnEntryPoint來處理這些異常。 但這沒有用。

我發現我的自定義AbstractAuthenticationProcessingFilter正在緩存Provider上引發的身份驗證異常。 我試圖重新拋出異常,但入口點沒有緩存它。

現在,我正在解決unsuccessfulAuthentication身份驗證 function 上的AbstractAuthenticationProcessingFilter上的這些異常:

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException failed) throws IOException, ServletException {
    int status = ...
    String jsonString = ...
    response.setStatus(status);
    response.setContentType("application/json");
    response.getWriter().write(jsonString); 
}

我不太喜歡這種解決方案,並且更願意將這些異常與AbstractAuthenticationProcessingFilter分開處理。

異常由ExceptionTranslationFilter處理。

  • 如果異常是org.springframework.security.core.AuthenticationException類型(任何子類),它將流入AuthenticationEntryPoint ,聽起來你不是這種情況。
  • 如果異常是org.springframework.security.access.AccessDeniedException類型(或子類),它將流入AccessDeniedHandler
  • 任何其他異常將被重新拋出。

如果您希望處理“任何其他”類別中的某些內容,您可以在過濾器鏈的更高位置實現自己的過濾器,或者按照您所做的那樣處理它。 有關詳細信息,請參閱有關ExceptionTranslationFilter的部分。 以下是 class的實現方式。

注意:正如其他評論者所指出的,如果您的 JWT 需求有開箱即用的解決方案,通常建議堅持“離家近”。 但實施過濾器以添加到 Spring 安全過濾器鏈是擴展 Spring 安全功能以適應您自己的應用程序的絕佳方式。 在許多用例中,您會發現這是一種有用(且必要)的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM