使用 JWT 生成 Token 代码示例

JSON Web Token,简称 JWT, 是一个开放的标准(RFC 7519),它定义了以一种紧凑的、自包含的 JSON 对象在各方之间安全传输信息的方式。该信息含有数字签名,可以被验证和信任。

JWT的介绍这里就不说了,想了解的可以看一下这边博客:JSON Web Token 入门教程

或者直接参考官方网站:https://jwt.io

项目是SpringBoot2.0,下面直接上代码。

Maven配置:

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

JWT工具:

这里使用了自定义字段和官方建议字段

package com.example.demo.util;

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;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @date 2019/4/25 11:46
 * @atuther wangbo
 */
public class JwtUtil {

    //密钥
    public static final String SECRET = "sdjhakdhajdklsl;o653632";
    //过期时间:秒
    public static final int EXPIRE = 5;

    /**
     * 生成Token
     * @param userId
     * @param userName
     * @return
     * @throws Exception
     */
    public static String createToken(String userId, String userName) throws Exception {
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.SECOND, EXPIRE);
        Date expireDate = nowTime.getTime();

        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String token = JWT.create()
                .withHeader(map)//
                .withClaim("userId", userId)
                .withClaim("userName", userName)
                .withSubject("测试")//
                .withIssuedAt(new Date())//签名时间
                .withExpiresAt(expireDate)//过期时间
                .sign(Algorithm.HMAC256(SECRET));//签名
        return token;
    }

    /**
     * 验证Token
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token)throws Exception{
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        }catch (Exception e){
            throw new RuntimeException("凭证已过期,请重新登录");
        }
        return jwt.getClaims();
    }

    /**
     * 解析Token
     * @param token
     * @return
     */
    public static Map<String, Claim> parseToken(String token){
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaims();
    }

}

测试类:

    public static void main(String[] args){
        try {
            String token = JwtUtil.createToken("12345", "wangbo");
            System.out.println("token=" + token);
            //Thread.sleep(5000);
            Map<String, Claim> map = JwtUtil.verifyToken(token);
            //Map<String, Claim> map = JwtUtil.parseToken(token);
            //遍历
            for (Map.Entry<String, Claim> entry : map.entrySet()){
                if (entry.getValue().asString() != null){
                    System.out.println(entry.getKey() + "===" + entry.getValue().asString());
                }else {
                    System.out.println(entry.getKey() + "===" + entry.getValue().asDate());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

测试结果:

token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiLmtYvor5UiLCJ1c2VyTmFtZSI6IndhbmdibyIsImV4cCI6MTU1NjE3NjYwNiwidXNlcklkIjoiMTIzNDUiLCJpYXQiOjE1NTYxNzY2MDF9.FNVh-NbFHgScsbbuwLvQL-sOqLuaAoI8jxMvudq81J8
sub===测试
userName===wangbo
exp===Thu Apr 25 15:16:46 CST 2019
userId===12345
iat===Thu Apr 25 15:16:41 CST 2019

基本就是这些了。

posted @ 2019-04-25 15:29  一线大码  Views(13374)  Comments(4Edit  收藏  举报