亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot集成JWT的工具類與攔截器實現方式

 更新時間:2024年01月12日 15:04:29   作者:龍域、白澤  
這篇文章主要介紹了SpringBoot集成JWT的工具類與攔截器實現方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

導入依賴

<!--引入JWT-->
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.4.0</version>
</dependency>

配置文件

# token配置
token:
  jwt:
    # 令牌自定義標識
    header: Authorization
    # 令牌密鑰
    secret: ">?N<:{LWPWXX#$%()(#*!()!KL<><MQLMNQNQJQK sdfkjsdrow32234545fdf"
    # 令牌有效期,單位分鐘(默認30分鐘)
    expireTime: 30

Jwt工具類

包括token的生成,token的驗證并返回存在負載中的用戶信息

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
import com.auth0.jwt.JWTCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
 
/**
 * 登錄Token的生成和解析
 */
@Component
public class JwtUtils {
 
    /**
     * token秘鑰
     */
    public static String SECRET = "";
 
    /**
     * token 過期時間單位
     */
    public static final int calendarField = Calendar.MINUTE;
 
    /**
     * token 過期時間
     */
    public static int calendarInterval = 30;
 
    @Value("${token.jwt.secret}")
    public void setSECRET(String SECRET) {
        JwtUtils.SECRET = SECRET;
    }
 
    @Value("${token.jwt.expireTime}")
    public  void setCalendarInterval(int calendarInterval) {
        JwtUtils.calendarInterval = calendarInterval;
    }
 
    /**
     * JWT生成Token.<br/>
     * <p>
     * JWT構成: header, payload, signature
     *
     * @param map 登錄成功后用戶信息
     */
    public static String createToken(Map<String,String> map) {
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();
 
        // header Map
        Map<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
 
        // 創(chuàng)建 token
        // param backups {iss:Service, aud:APP}
        JWTCreator.Builder builder = JWT.create().withHeader(header); // header 
 
        map.forEach(builder::withClaim); // payload
        // 指定token過期簽名 和 簽名
        return builder.withExpiresAt(expiresDate).sign(Algorithm.HMAC256(SECRET));
    }
 
    /**
     * 解密token
     * @param token 傳入的token
     * @return 解密后的結果
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            // token 校驗失敗, 拋出Token驗證非法異常
             e.printStackTrace();
        }
        assert jwt != null;
        return jwt.getClaims();
    }
}

定義攔截器

對需要token驗證的接口進行攔截

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lixianhe.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
 
@Component
public class JWTInterceptor implements HandlerInterceptor {
 
    @Value("${token.jwt.heade}r")
    private String header;
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        // 獲取請求頭中的token
        String token = request.getHeader(header);
        if(token ==null){
            response.setStatus(401);
            return false;
        }
        try {
            // 驗證token,返回token中的信息
            JwtUtils.verifyToken(token);
            return true;
        }catch (SignatureVerificationException e){
            map.put("msg","無效簽名");
        } catch (TokenExpiredException e){
            map.put("msg","token過期");
        }catch (AlgorithmMismatchException e){
            map.put("msg","簽名算法不一致");
        }catch (Exception e){
            map.put("msg","token無效");
        }
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}

配置攔截器

配置對哪些路徑攔截,哪些路徑放行

import com.lixianhe.intercept.JWTInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
 
    @Autowired
    private JWTInterceptor jwtInterceptor;
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/index") // 攔截
                .excludePathPatterns("/hello"); // 不攔截
    }
}

總結

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • Spring MVC 擴展和 SSM 框架整合步驟詳解

    Spring MVC 擴展和 SSM 框架整合步驟詳解

    在前端頁面后后臺交互的過程中,需要一種格式清晰、高效且兩端都可以輕松使用的數據格式做交互的媒介,JSON正可以滿足這一需求,下面學習使用Spring MVC 框架處理JSON數據,感興趣的朋友一起看看吧
    2024-08-08
  • 數組實現Java 自定義Queue隊列及應用操作

    數組實現Java 自定義Queue隊列及應用操作

    這篇文章主要介紹了數組實現Java 自定義Queue隊列及應用操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • SpringBoot MDC全鏈路調用日志跟蹤實現詳解

    SpringBoot MDC全鏈路調用日志跟蹤實現詳解

    這篇文章主要為大家介紹了SpringBoot MDC全鏈路調用日志跟蹤實現詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-02-02
  • Spring Boot創(chuàng)建可執(zhí)行jar包的實例教程

    Spring Boot創(chuàng)建可執(zhí)行jar包的實例教程

    這篇文章主要介紹了Spring Boot創(chuàng)建可執(zhí)行jar包的實例教程,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-02-02
  • Java中用戶向系統(tǒng)傳遞參數的三種基本方式實例分享

    Java中用戶向系統(tǒng)傳遞參數的三種基本方式實例分享

    這篇文章主要介紹了Java中用戶向系統(tǒng)傳遞參數的三種基本方式實例,有需要的朋友可以參考一下
    2014-01-01
  • Maven?pom.xml文件獲取當前時間戳方式

    Maven?pom.xml文件獲取當前時間戳方式

    這篇文章主要介紹了Maven?pom.xml文件獲取當前時間戳方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • SpringBoot項目開發(fā)中常用的依賴

    SpringBoot項目開發(fā)中常用的依賴

    這篇文章主要介紹了SpringBoot項目開發(fā)中常用的依賴詳解,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-06-06
  • nacos服務注冊服務發(fā)現依賴配置詳解

    nacos服務注冊服務發(fā)現依賴配置詳解

    這篇文章主要為大家介紹了nacos服務注冊服務發(fā)現依賴配置詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-09-09
  • java解決動態(tài)配置字段需求問題

    java解決動態(tài)配置字段需求問題

    這篇文章主要介紹了java解決動態(tài)配置字段需求問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • 實例講解spring boot 多線程

    實例講解spring boot 多線程

    這篇文章主要介紹了spring boot 多線程的相關資料,文中示例代碼非常詳細,幫助大家更好的理解和學習,感興趣的朋友可以了解下
    2020-07-07

最新評論