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

SpringBoot集成JWT的工具類與攔截器實現(xiàn)方式

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

導入依賴

<!--引入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"); // 不攔截
    }
}

總結

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

相關文章

最新評論