java jjwt-api使用,java jwt使用,java jwt 工具類


java jjwt-api使用,java jwt使用,java jwt 工具類,Java Web Token工具類

Springboot jwt整合

 

================================

©Copyright 蕃薯耀 2020-12-02

https://www.cnblogs.com/fanshuyao/

 

一、引入jjwt-api依賴

<properties>
    <!-- 構建時編碼 -->    
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!-- 輸出時編碼 -->
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <!-- JDK版本 -->
    <java.version>1.8</java.version>
    <jjwt.version>0.11.2</jjwt.version>
</properties>

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>${jjwt.version}</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>${jjwt.version}</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId>
    <version>${jjwt.version}</version>
    <scope>runtime</scope>
</dependency>

 

二、 jjwt-api實現工具類

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.lqy.study.exception.RunException;
import com.lqy.study.utils.DateUtils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.MissingClaimException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.io.Decoders;

@Component
public class JwtUtils {

    private static Logger log = Logger.getLogger(JwtUtils.class);
    
    
    private static String secretKey;
    
    private static String aa;//測試靜態變量注入
    
    /**
     * 靜態變量注入
     * 從配置文件讀取jjwt.key屬性
     * 注入key,set方法不能是static
     * @param secretKey
     */
    @Value("${jjwt.key}")
    public void setSecretKey(String secretKey) {
        JwtUtils.secretKey = secretKey;
    }
    
    
    /**
     * 靜態實體變量注入
     * jjwtProperties需要配置:@ConfigurationProperties(prefix = "jjwt", ignoreUnknownFields = true)
     * @param jjwtProperties
     */
    @Autowired
    public void setSecretKey(JjwtProperties jjwtProperties) {
        JwtUtils.aa = jjwtProperties.getKey();
    }


    private static String KEY_CLAIMS = "key_claims";
    private static String SUBJECT = "key_subject";
    
    private JwtUtils(){
        
    }
    
    
    /**
     * 生成token
     * @return
     * @throws ParseException
     */
    public static String getToken() throws ParseException {
        //Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        
        log.info("aa===" + aa);
        
        
        Date now = new Date();
        Date expirationDate = DateUtils.addMinute(null, 2);//增加2分鍾的過期時間,用於測試
        
        log.info("now===" + DateUtils.formatDateTime(now));
        log.info("expirationDate===" + DateUtils.formatDateTime(expirationDate));
        
        Map<String, Object> claims = new HashMap<String, Object>();
        User user = new User();
        user.setId(1000L);
        user.setName("張三");
        claims.put(KEY_CLAIMS, user);
        
        String token = Jwts.builder()
                        .setClaims(claims)//必須放最前面,不然后面設置的東西都會沒有:如setExpiration會沒有時間
                        .setId(UUID.randomUUID().toString())
                        .setSubject(SUBJECT)
                        .setIssuedAt(now)
                        .setExpiration(expirationDate)//過期時間
                        .signWith(SignatureAlgorithm.HS256, getSecretKey())
                        .compact();
        
        log.info("token===" + token);
        
        return token;
    }
    
    
    /**
     * 解析token,並返回User對象
     * @param token
     * @return
     * @throws ParseException
     */
    public static User parseToken(String token) throws ParseException {
        
        String msg = null;
        try {
            Jws<Claims> jws = Jwts.parser()
                    .setSigningKey(getSecretKey())
                    .requireSubject(SUBJECT)//校驗必須有這個屬性,可以省略這步
                    .parseClaimsJws(token);
    
            Claims claims = jws.getBody();//Claims是一個Map
            
            log.info("claims===" + JSONUtil.toJsonStr(claims));
            log.info("claims.getIssuedAt()===" + claims.getIssuedAt());
            log.info("claims.getExpiration()===" + claims.getExpiration());
            
            //map轉實體
            User user = BeanUtil.toBean(claims.get(KEY_CLAIMS), User.class);
            log.info("user===" + JSONUtil.toJsonStr(user));
            
            return user;
            
            
        }catch (SignatureException se) {
            msg = "密鑰錯誤";
            log.error(msg, se);
            throw new RunException(msg);
            
        }catch (MalformedJwtException me) {
            msg = "密鑰算法或者密鑰轉換錯誤";
            log.error(msg, me);
            throw new RunException(msg);
            
        }catch (MissingClaimException mce) {
            msg = "密鑰缺少校驗數據";
            log.error(msg, mce);
            throw new RunException(msg);
            
        }catch (ExpiredJwtException mce) {
            msg = "密鑰已過期";
            log.error(msg, mce);
            throw new RunException(msg);
            
        }catch (JwtException jwte) {
            msg = "密鑰解析錯誤";
            log.error(msg, jwte);
            throw new RunException(msg);
        }
        
    }
    
    
    /**
     * 獲取自定義密鑰
     * @return
     */
    private static byte[] getSecretKey() {
        //log.info("secretKey = " + secretKey);
        if(StringUtils.isBlank(secretKey)) {
            throw new RunException("jjwt配置的密鑰不能為空");
        }
        return Decoders.BASE64.decode(secretKey);
    }
    
    
    public static void main(String[] args) throws Exception {
        getToken();
    }

    
}

 

User類:

public class User {

    private Long id;
    private String name;
    
    
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + "]";
    }
}

 

三、科普springboot靜態變量注入的方式

1、靜態變量secretKey通過配置文件application.properties的屬性注入,並使用base64編碼,取出來的時候,需要解碼(配置文件的屬性也可以不編碼,直接取出來)

jjwt.key=aXNsZWVfaGFoYQ==

 

注入方式:方法加注解@Value("${jjwt.key}"),變量作為參數

/**
 * 靜態變量注入
 * 從配置文件讀取jjwt.key屬性
 * 注入key,set方法不能是static
 * @param secretKey
 */
@Value("${jjwt.key}")
public void setSecretKey(String secretKey) {
    JwtUtils.secretKey = secretKey;
}

 

2、靜態實體變量 jjwtProperties 注入,同樣通過通過配置文件application.properties的屬性注入,但可以直接配置多個屬性(僅用於學習,可忽略):

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "jjwt", ignoreUnknownFields = true)
public class JjwtProperties {

    private String key;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
}

 

注入的方式:方法加上@Autowired注解,實體作為參數

/**
 * 靜態實體變量注入
 * jjwtProperties需要配置:@ConfigurationProperties(prefix = "jjwt", ignoreUnknownFields = true)
 * @param jjwtProperties
 */
@Autowired
public void setSecretKey(JjwtProperties jjwtProperties) {
    JwtUtils.aa = jjwtProperties.getKey();
}

 

 

springboot 整合java-jwt:

https://www.cnblogs.com/fanshuyao/p/14079488.html

 

 

(如果文章對您有幫助,歡迎捐贈,^_^)

 

================================

©Copyright 蕃薯耀 2020-12-02

https://www.cnblogs.com/fanshuyao/

 


免責聲明!

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



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