java jwt使用,springboot 整合java-jwt,java jwt工具类

java jwt使用,springboot 整合java-jwt,java jwt工具类

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

©Copyright 蕃薯耀 2020-12-03

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

一、引入java-jwt的maven依赖

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.11.0</version>
</dependency>

二、springboot自定义配置文件(jwt.properties)配置密钥

1、jwt.properties

jwt.key=and0X3ZhbGlkYXRpb25fY29uZmlnX2tleQ==

2、springboot自定义配置文件之类配置文件:JwtProperties.java,读取jwt.properties配置的密钥

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource(value = {"jwt.properties"}, encoding = "UTF-8")
@ConfigurationProperties(ignoreUnknownFields = true, prefix = "jwt")
public class JwtProperties {

    private String key;

    public String getKey() {
        return key;
    }

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

三、java jwt工具类:JwtUtils.java

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

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
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.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lqy.study.exception.RunException;
import com.lqy.study.utils.DateUtils;

import cn.hutool.json.JSONUtil;

@Component
public class JwtUtils {

    private static Logger log = Logger.getLogger(JwtUtils.class);
    
    
    private static String secretKey;
    private static String KEY_JWT_CLAIMS = "key_jwt_claims";
    private static String KEY_USER = "key_user";
    private static String KEY_JAVA_JWT = "key_java_jwt";
    
    private JwtUtils(){
        
    }
    
    
    /**
     * 静态实体变量注入
     * @param jwtProperties JwtProperties
     * jwtProperties需要配置:@ConfigurationProperties(prefix = "jwt", ignoreUnknownFields = true)
     */
    @Autowired
    public void setSecretKey(JwtProperties jwtProperties) {
        JwtUtils.secretKey = jwtProperties.getKey();
    }

    
    /**
     * 生成token
     * @return
     * @throws ParseException
     */
    public static String getToken() throws ParseException {
        
        Date now = new Date();
        Date expiresDate = DateUtils.addMinute(null, 2);//增加2分钟的过期时间,用于测试
        
        log.info("now===" + DateUtils.formatDateTime(now));
        log.info("expiresDate===" + DateUtils.formatDateTime(expiresDate));
        
        User user = new User();
        user.setId(1100L);
        user.setName("老王2");
        
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put(KEY_USER, user);
        
        Algorithm algorithm = getAlgorithm();
        String token = JWT.create()
                            //.withClaim(KEY_JWT_CLAIMS, user.getId())//claims不能是Map<String, Object>
                            .withIssuer(KEY_JAVA_JWT)
                            .withIssuedAt(now)
                            .withHeader(claims)
                            //.withKeyId(UUID.randomUUID().toString())
                            .withExpiresAt(expiresDate)
                            .sign(algorithm);
        
        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 {
            Algorithm algorithm = getAlgorithm();
            
            JWTVerifier verifier = JWT.require(algorithm)
                                        .withIssuer(KEY_JAVA_JWT)
                                        .build();
            
            DecodedJWT jwt = verifier.verify(token);
            
            String payload = jwt.getPayload();
            Map<String, Claim> claims = jwt.getClaims();
            User user = jwt.getHeaderClaim(KEY_USER).as(User.class);
            Long userId = claims.get(KEY_JWT_CLAIMS) == null ? null : claims.get(KEY_JWT_CLAIMS).asLong();
            
            log.info("payload===" + payload);
            log.info("claims===" + JSONUtil.toJsonStr(claims));
            log.info("userId===" + JSONUtil.toJsonStr(userId));
            log.info("user===" + JSONUtil.toJsonStr(user));
            
            return user;
            
            
        }catch (JWTDecodeException de) {
            msg = "密钥格式不正确";
            log.error(msg, de);
            throw new RunException(msg);
            
        }catch (SignatureVerificationException de) {
            msg = "密钥签证不正确";
            log.error(msg, de);
            throw new RunException(msg);
            
        }catch (TokenExpiredException tee) {
            msg = "密钥已过期";
            log.error(msg, tee);
            throw new RunException(msg);
            
        }catch (InvalidClaimException ice) {
            msg = "非法密钥";
            log.error(msg, ice);
            throw new RunException(msg);
            
        }catch (JWTVerificationException jwte) {
            msg = "密钥解析错误";
            log.error(msg, jwte);
            throw new RunException(msg);
        }
        
    }
    
    
    /**
     * 获取自定义密钥
     * @return
     */
    private static Algorithm getAlgorithm(){
        return Algorithm.HMAC256(getSecretKeyString());
    }
    
    
    /**
     * 获取自定义密钥
     * @return
     */
    private static byte[] getSecretKey(){
        //log.info("secretKey===" + secretKey);
        if(StringUtils.isBlank(secretKey)) {
            throw new RunException("jwt配置的密钥不能为空");
        }
        return Base64.getDecoder().decode(secretKey);
    }
    
    
    /**
     * 获取自定义密钥
     * @return
     */
    private static String getSecretKeyString(){
        String secretKeyString = new String(getSecretKey());
        //log.info("secretKeyString===" + secretKeyString);
        return secretKeyString;
    }
    
    
    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 + "]";
    }
}

四、java jwt获取token和token验证

import java.text.ParseException;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lqy.study.bean.Result;
import com.lqy.study.biz.jjwt.JwtUtils;

@RestController
@RequestMapping("/jwt")
public class JwtController {

    
    @RequestMapping("/get")
    public Result get() throws ParseException {
        return Result.ok(JwtUtils.getToken());
    }
    
    
    @RequestMapping("/parse")
    public Result parse(String token) throws ParseException {
        return Result.ok(JwtUtils.parseToken(token));
    }
    
}

java jjwt-api使用见:

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

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

©Copyright 蕃薯耀 2020-12-03

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

原文地址:https://www.cnblogs.com/fanshuyao/p/14079488.html