自定義Spring Security的身份驗證失敗處理


1.概述

在本快速教程中,我們將演示如何在Spring Boot應用程序中自定義Spring Security的身份驗證失敗處理。目標是使用表單登錄方法對用戶進行身份驗證。

2.認證和授權(Authentication and Authorization)

身份驗證和授權通常結合使用,因為它們在授予系統訪問權限時起着重要且同樣重要的作用

但是,它們具有不同的含義,並在驗證請求時應用不同的約束

  • 身份驗證 - 在授權之前;它是關於驗證收到的憑證;我們驗證用戶名和密碼是否與我們的應用程序識別的用戶名和密碼相匹配
  • 授權 - 用於驗證成功通過身份驗證的用戶是否有權訪問應用程序的某個功能

我們可以自定義身份驗證和授權失敗處理,但是,在此應用程序中,我們將專注於身份驗證失敗。

3. Spring Security的AuthenticationFailureHandler

Spring Security提供了一個默認處理身份驗證失敗的組件。

但是,我們發現於默認行為不足以滿足實際要求的情況是很常見的。
如果是這種情況,我們可以創建自己的組件並通過實現AuthenticationFailureHandler接口提供我們想要的自定義行為

public class CustomAuthenticationFailureHandler 
  implements AuthenticationFailureHandler {
  
    private ObjectMapper objectMapper = new ObjectMapper();
 
    @Override
    public void onAuthenticationFailure(
      HttpServletRequest request,
      HttpServletResponse response,
      AuthenticationException exception) 
      throws IOException, ServletException {
  
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        Map<String, Object> data = new HashMap<>();
        data.put(
          "timestamp", 
          Calendar.getInstance().getTime());
        data.put(
          "exception", 
          exception.getMessage());
 
        response.getOutputStream()
          .println(objectMapper.writeValueAsString(data));
    }
}

默認情況下,Spring使用包含錯誤信息的請求參數將用戶重定向回登錄頁面

在此應用程序中,我們將返回401響應,其中包含有關錯誤的信息以及錯誤發生的時間戳。

  • DelegatingAuthenticationFailureHandler將AuthenticationException子類委托給不同的AuthenticationFailureHandler,這意味着我們可以為AuthenticationException的不同實例創建不同的行為
  • ExceptionMappingAuthenticationFailureHandler根據AuthenticationException的完整類名將用戶重定向到特定的URL
  • 無論AuthenticationException的類型如何,ForwardAuthenticationFailureHandler都會將用戶轉發到指定的URL
  • SimpleUrlAuthenticationFailureHandler是默認使用的組件,如果指定,它會將用戶重定向到failureUrl;否則,它只會返回401響應

現在我們已經創建了自定義AuthenticationFailureHandler,讓我們配置我們的應用程序並覆蓋Spring的默認處理程序

@Configuration
@EnableWebSecurity
public class SecurityConfiguration 
  extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) 
      throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("baeldung")
          .password("baeldung")
          .roles("USER");
    }
 
    @Override
    protected void configure(HttpSecurity http) 
      throws Exception {
        http
          .authorizeRequests()
          .anyRequest()
          .authenticated()
          .and()
          .formLogin()
          .failureHandler(customAuthenticationFailureHandler());
    }
 
    @Bean
    public AuthenticationFailureHandler customAuthenticationFailureHandler() {
        return new CustomAuthenticationFailureHandler();
    }
}

注意failureHandler()調用,我們可以告訴Spring使用我們的自定義組件而不是使用默認組件。

4.結論

在此示例中,我們使用Spring的AuthenticationFailureHandler接口自定義了應用程序的身份驗證失敗處理程序

在Github項目中找到此示例的實現

在本地運行時,您可以在localhost:8080上訪問和測試應用程序.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM