Spring Security実戦乾物:登録してJWT Tokenに戻る


1.はじめに
Spring Security実戦乾物シリーズの記事をお読みください.前文ではJWTツールを実現しました.本稿では、JWTとSpring Securityを組み合わせて、認証に成功した後、指定したページにジャンプせずにJWT Tokenに戻る方法について説明します.本明細書のDEMOは、文末によって取得することができる
2.プロセス
JWTは前後端分離に適している.私たちはログインに成功した後、トップページにジャンプしないで、JWT Tokenペア(DEMOではJwtTokenPair)に直接戻り、ログインに失敗した後、認証失敗に関する情報を返します.
3.ログイン成功/失敗を実現するためのリターンロジック
Spring Securityの実戦干物を見たことがある場合は、カスタムログインをプレイすると、次の方法が理解しやすくなります.
3.1 AuthenticationSuccessHandler JWT Tokenに戻るAuthenticationSuccessHandlerはログイン成功後のロジックを処理するために使用され、Spring IoCコンテナを実装し、注入する.
     /**
      *           JWT Token  .
      *
      * @param jwtTokenGenerator the jwt token generator
      * @return the authentication success handler
      */
     @Bean
     public AuthenticationSuccessHandler authenticationSuccessHandler(JwtTokenGenerator jwtTokenGenerator) {
         return (request, response, authentication) -> {
             if (response.isCommitted()) {
                 log.debug("Response has already been committed");
                 return;
             }
             Map map = new HashMap<>(5);
             map.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
             map.put("flag", "success_login");
             User principal = (User) authentication.getPrincipal();
 
             String username = principal.getUsername();
             Collection authorities = principal.getAuthorities();
             Set roles = new HashSet<>();
             if (CollectionUtil.isNotEmpty(authorities)) {
                 for (GrantedAuthority authority : authorities) {
                     String roleName = authority.getAuthority();
                     roles.add(roleName);
                 }
             }
 
             JwtTokenPair jwtTokenPair = jwtTokenGenerator.jwtTokenPair(username, roles, null);
 
             map.put("access_token", jwtTokenPair.getAccessToken());
             map.put("refresh_token", jwtTokenPair.getRefreshToken());
 
             ResponseUtil.responseJsonWriter(response, RestBody.okData(map, "    "));
         };
     }

3.2 AuthenticationFailureHandler認証失敗情報を返すAuthenticationFailureHandlerは認証に失敗した後のロジックを処理し、フロントエンドはこれに基づいてジャンプ処理ロジックを行い、Spring IoCコンテナに注入する.
    /**
     *                                    
     *
     * @return the authentication failure handler
     */
    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return (request, response, exception) -> {
            if (response.isCommitted()) {
                log.debug("Response has already been committed");
                return;
            }
            Map map = new HashMap<>(2);

            map.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            map.put("flag", "failure_login");
            ResponseUtil.responseJsonWriter(response, RestBody.build(HttpStatus.UNAUTHORIZED.value(), map, "    ","-9999"));
        };
    } 

4.構成
上記の2つのHandler Beanをログイン構成に書き込みます.関連する断片は以下の通りです.詳細は文末DEMOを参照してください.
 httpSecurity.formLogin().loginProcessingUrl(LOGIN_PROCESSING_URL).successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler)

5.検証
Spring Security実戦ドライ:カスタムログインの章6.4テストをプレイして実行します.結果は次のとおりです.
5.1ログイン成功結果
 {
     "httpStatus": 200,
     "data": {
         "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbGwiLCJhdWQiOiJGZWxvcmRjbiIsInJvbGVzIjoiW10iLCJpc3MiOiJmZWxvcmQuY24iLCJleHAiOiIyMDE5LTExLTI3IDExOjMxOjMyIiwiaWF0IjoiMjAxOS0xMC0yOCAxMTozMTozMiIsImp0aSI6IjdmYTBlOWFiYjk5OTRjZGRhNGM5NjI4YzExNGM3YTk4In0.PvVsc8w10_0C5UIifJS1S5dEia5PQoVc_6wMfLAZOf574kt-VopHBVEp2zkjC1CNN3ltchy5rx6samaBDQvqWgoeFLXbRgNOa9Qhdf0wMLf-pUqoKRHuhBZV9HsvXSyQCFjZWlIguv4FSPZhbEff6D_8QUXmdWjlF_XEG2BPMr4",
         "refresh_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhbGwiLCJhdWQiOiJGZWxvcmRjbiIsInJvbGVzIjoiW10iLCJpc3MiOiJmZWxvcmQuY24iLCJleHAiOiIyMDIwLTAxLTI2IDExOjMxOjMyIiwiaWF0IjoiMjAxOS0xMC0yOCAxMTozMTozMiIsImp0aSI6IjdmYTBlOWFiYjk5OTRjZGRhNGM5NjI4YzExNGM3YTk4In0.Caj4AAothdUwZAFl8IjcAZmmXHgTt76z8trVG1sf_WHZucFVcHR8FWjShhITpArsQpmokP6GBTMsCvWDl08fUVZBpOWc1CdPUAIIEdArHCFzO64HXc_DLSyg9v0C-qYfxaTlf0npL5QxpBBr9sJcyzxZF3CnpfZpAxm8WZzXG6o",
         "time": "2019-10-28 11:32:11",
         "flag": "success_login"
     },
     "msg": "    ",
     "identifier": ""
 }
access_tokenを用いて、公式サイトjwt.ioが提供する復号機能を用いて、以下のように復号する.
5.2ログイン失敗結果
 {
     "httpStatus": 401,
     "data": {
         "time": "2019-10-28 12:54:10",
         "flag": "failure_login"
     },
     "msg": "    ",
     "identifier": "-9999"
 }

6.まとめ
今日はJWTとSpring Securityを連絡し、ログインに成功したらJWT Tokenに戻ります.これはほんの始まりです.次の記事では、クライアントがJWT Tokenを使用する方法、サービス側がJWT Tokenを検証する方法について説明します.注目してください.
文書に関連するDEMOは、公衆番号:Felordcnに注目し、ss06に返信することによって取得することができる. :Felordcn
個人ブログ:https://felord.cn