SpringSecurityカスタムUsernamePasswordAuthenticationFilter

UsernamePasswordAuthenticationFilter介绍

UsernamePasswordAuthenticationFilterは、カスタマイズされたフィルタしばらく認証用のユーザ名とパスワードの入力をAbstractAuthenticationProcessingFilterです。その役割は、()http.formLoginを呼び出すときに、デフォルトのログイン要求パターンは、「/ログイン」で追加され、POSTリクエストのために。我々はloginProcessingUrlにマッチしている、ログインすると、このフィルタは、認証マネージャauthenticationManagerログインを検証するために委託されます。

カスタムUsernamePasswordAuthenticationFilter

ここで私は、カスタムしてパスワードを解読するために、フロントUsernamePasswordAuthenticationFilterは、RSA秘密鍵上を通過実現することである、とログインアドレスは「/ログイン」ではないので、その継承AbstractAuthenticationProcessingFilter、デフォルトのログインアドレスの場合は、再直接の後継UsernamePasswordAuthenticationFilterできる必要があります書き込みattemptAuthentication方法は、することができます。

パブリック クラス MyUsernamePasswordAuthenticationFilterは延びAbstractAuthenticationProcessingFilter {
     パブリック 静的 最終的な文字列SPRING_SECURITY_FORM_USERNAME_KEY =「ユーザ名」公共の 静的な 最終文字列SPRING_SECURITY_FORM_PASSWORD_KEY =「パスワード」;
    プライベート文字列usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY。
    プライベート文字列passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY。
    プライベート ブール postOnly = ;
    プライベート文字列のPrivateKey = "xxxxxxxxxxxxxxxxxxx"; 
    
    公共MyUsernamePasswordAuthenticationFilter(){
         スーパー AntPathRequestMatcher( "/ OAuthの/トークン"、 "POST" )); 
    } 

    パブリック認証attemptAuthentication(HttpServletRequestのリクエスト、HttpServletResponseの応答)を
             スローして、AuthenticationException {
         場合(postOnly && request.getMethodを()等号( "POST"!。{))
             スロー 新しい AuthenticationServiceException( "サポートされていない認証方法:" + request.getMethodを() ); 
        } 
        文字列名 = obtainUsername(リクエスト)。= obtainPassword(リクエスト)。
        試す{ 
            パスワード = RSAUtil.decrypt(パスワード、のPrivateKey)。
        } キャッチ(例外e){ 
            e.printStackTrace(); 
        } 

        であれば(ユーザ名== NULL ){ 
            ユーザー名 = "" ; 
        } 
        
        もし(パスワード== NULL ){ 
            パスワード = "" ; 
        } 
 = username.trim()。

        UsernamePasswordAuthenticationTokenてauthrequest = 新しいですUsernamePasswordAuthenticationToken(ユーザ名、パスワード); 

        // サブクラスは、「詳細」プロパティを設定することを許可する
        setDetails(リクエスト、てauthrequestを)。

        戻る スーパー.getAuthenticationManagerを()(てauthrequest)を認証。
    } 

    公共 ボイドsetAuthenticationManager(AuthenticationManager authenticationManager){
         スーパー.setAuthenticationManager(authenticationManager)。
    } 
    
    保護された文字列obtainPassword(HttpServletRequestのリクエスト){
         返す request.getParameter(passwordParameter).replaceAllを(」」、 "+" )。
    } 

    保護ストリングobtainUsername(HttpServletRequestのリクエスト){
         戻りrequest.getParameter(usernameParameter)。
    } 

    保護された ボイドsetDetails(HttpServletRequestのリクエスト、
            UsernamePasswordAuthenticationTokenてauthrequest){ 
        authRequest.setDetails(authenticationDetailsS​​ource.buildDetails(リクエスト))。
    } 

    公共 ボイドsetUsernameParameter(文字列usernameParameter){ 
        Assert.hasText(usernameParameter、 "ユーザ名パラメータが空またはnullであってはなりません" )。
        この .usernameParameter = usernameParameter。
    } 

    公共 のボイドsetPasswordParameter(文字列passwordParameter){ 
        Assert.hasText(passwordParameter、 "パスワードのパラメータが空またはnullであってはなりません" )。
        この .passwordParameter = passwordParameter。
    } 
    
    公共 ボイド setPostOnly(ブールpostOnly){
         この .postOnly = postOnly。
    } 

    公共の 最終的な文字列getUsernameParameter(){
         リターンusernameParameter。
    } 

    公共の 最終的な文字列getPasswordParameter(){
         リターンpasswordParameter。
    } 

}

MyUsernamePasswordAuthenticationFilterは、カスタムフィルタチェーンフィルタチェーンに追加しました

http.addFilterAtを使用する(myAuthenticationFilter()、UsernamePasswordAuthenticationFilter.class)SpringSecurityカスタムフィルタUsernamePasswordAuthenticationFilter位置にクラス内に配置され、認証の成功と失敗の処理方法を設定するために、認証マネージャAuthenticationManager

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = パブリック クラス SecurityConfigは延びWebSecurityConfigurerAdapter { 
    
    @Autowired 
    プライベートAuthenticationSuccessHandler appLoginInSuccessHandlerと、
    
    @Bean 
    @Override 
    公共 AuthenticationManager authenticationManagerBean()がスロー例外{ 
        AuthenticationManagerマネージャ = スーパー.authenticationManagerBeanを();
        リターン・マネージャ; 
    } 
    @Overrideは
    保護され 、ボイド(HttpSecurity HTTP)を設定スロー例外{ 
        (認証)(anyRequest。http.authorizeRequestsを())
                .AND()。httpBasic()および()
                frameOptions。.cors())(無効ヘッダ()()。 sameOrigin(); // 解决IFRAME无法访问 
        http.addFilterAt(myAuthenticationFilter()、UsernamePasswordAuthenticationFilter。クラス); 
    } 

    @Bean 
MyUsernamePasswordAuthenticationFilter myAuthenticationFilter()スロー例外{ 
        MyUsernamePasswordAuthenticationFilterフィルタ = 新しい MyUsernamePasswordAuthenticationFilterを();
        filter.setAuthenticationManager(authenticationManagerBean())。
        filter.setAuthenticationSuccessHandler(appLoginInSuccessHandler)。
        filter.setAuthenticationFailureHandler(新しいAuthenticationFailureHandler(){ 
            @Override 
            公共 ボイド onAuthenticationFailure(HttpServletRequestのリクエスト、HttpServletResponseの応答含むAuthenticationException e)はスローにIOException、ServletExceptionが{ 
                response.setContentTypeは( "アプリケーション/ JSON;のcharset = UTF-8" ); 
                response.getWriterを( ).WRITE(JSON.toJSONString(Respon.failed( "失败登录!" ))); 
            } 
        });
        リターンフィルタ。
    } 
}

カスタムUsernamePasswordAuthenticationFilter使用

上記の例に加えて、一般にフォームログJSON形式になり、ログイン認証コードなどを変更するために使用され、デフォルトのログインのローカルアドレスであることに留意すべきUsernamePasswordAuthenticationFilter

 

おすすめ

転載: www.cnblogs.com/dang-/p/11535940.html