spring boot集成JWT算法

spring boot集成JWT算法

JWT算法,通常用于登录授权和信息交换。这里做简单的demo,具体使用,结合项目情况。

一、.JWT的结构

通俗来讲JWT由header.payload.signature三部分组成的字符串,网上有太多帖子介绍这一块了,所以在这里就简单介绍一下就好了。

1.1 header

header由使用的签名算法令牌的类型的组成。

1.2 payload

payload说直白一些就类似你的requestBody中的数据。

1.3 signature

如果要生成signature,就需要使用jwt自定义配置项中的secret,也就是Hmac算法加密所需要的密钥。

二、使用

2.1导包

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

2.2 token工具

包含创建token,验证token,解析token. 封装成工具,在项目中直接调用。

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 测试JWT加密算法,并且解密
 */
public class JWTUtil {
    private static final Logger logger = LoggerFactory.getLogger(JWTUtil.class);
    /**
     * 密钥
     */
    private static final String SECRET = "my_secret_sdgdsgfdgkfgjrigfhpbg156456";

    /**
     * 过期时间
     **/
    private static final long EXPIRATION = 1800L;//单位为秒

    /**
     * 生成用户token,设置token超时时间
     */
    public static String createToken(String userId, String userName) {
        //过期时间
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                .withHeader(map)// 添加头部
                //可以将基本信息放到claims中,更具需要,可设置多个
                .withClaim("id", userId)//userId
                .withClaim("userName", userName)//userName
                .withExpiresAt(expireDate) //超时设置,设置过期的日期
                .withIssuedAt(new Date()) //签发时间
                .sign(Algorithm.HMAC256(SECRET)); //SECRET加密
        return token;
    }

    /**
     * 校验token并解析token
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);//到这里能够解析出来,说明token是正确的。
        }catch (JWTDecodeException e) {
            // token错误
            logger.error(e.getMessage());
        }catch (TokenExpiredException e) {
            // token过期
            logger.error(e.getMessage());
        }catch (Exception e) {
            logger.error(e.getMessage());
            logger.error("解码失败");
            //解码异常则抛出异常
            return null;
        }
        return jwt.getClaims();
    }

    //测试,并解密token中的内容
    public static void main(String[] args) {
        String token = createToken("11", "我的姓名");
        Map<String, Claim> map = verifyToken(token);
        Set<Map.Entry<String, Claim>> entrySet = map.entrySet();
        for (Map.Entry<String, Claim> entry : entrySet) {
            System.out.println(entry.getKey() + "=="+entry.getValue().asString());
        }
    }
}
发布了38 篇原创文章 · 获赞 3 · 访问量 1101

猜你喜欢

转载自blog.csdn.net/S_L__/article/details/104632597