Jwt生成,解析token,封装工具类

Json web token

  1. 导入jjwt依赖
 
            io.jsonwebtoken
            jjwt
            0.9.0
        
  1. 生成token,使用工具类Jwts的builder()方法,完成用户验证后返回token给客户端
public class CreateJwt {
    public static void main(String[] args) {
        JwtBuilder jwtBuilder = Jwts.builder().setId("88").setSubject("小白")
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "liang")
                //添加非私密的其它内容
                .claim("companyId","123456")
                .claim("companyName","腾讯");
        String token = jwtBuilder.compact();
        System.out.println(token);


    }
}
  1. 用户发送请求是携带token,解析token
public class ParseJwt {
    public static void main(String[] args) {
        String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4OCIsInN1YiI6IuWwj-eZvSIsImlhdCI6MTU5MTE4ODgyNiwiY29tcGFueUlkIjoiMTIzNDU2IiwiY29tcGFueU5hbWUiOiLohb7orq8ifQ.jwJbTI_qCW365JgTtxeGz_jFXyFtQ4be-OCp5ezR4n8";
        Claims claims = Jwts.parser().setSigningKey("liang").parseClaimsJws(token).getBody();
        System.out.println(claims.getId());
        System.out.println(claims.getSubject());
        System.out.println(claims.getIssuedAt());
        //解析自定义的claim中的内容
        String companyId = (String) claims.get("companyId");
        String companyName = (String) claims.get("companyName");
        System.out.println(companyId);
        System.out.println(companyName);
    }
}
  1. 将生成和解析封装成工具类
package com.springboot.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Getter
@Setter
@ConfigurationProperties("jwt.config")
@Component
public class JwtUtils {
    //签名私钥
    private String key;
    //签名有效时间
    private long ttl;

    public String createJwtToken(String id, String name, Map map){
        //设置失效时间
        //获取当前时间
        long now=System.currentTimeMillis();
        //当前时间+有效时间=过期时间
        long exp=now+ttl;
        //创建JwtBuilder

        JwtBuilder jwtBuilder = Jwts.builder().setId(id).setSubject(name)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, key);

        //根据map设置clamis
        jwtBuilder.setClaims(map);
        //设置失效时间
        jwtBuilder.setExpiration(new Date(exp));
        String token = jwtBuilder.compact();
        return token;
    }

    public Claims parseToken(String token){
        Claims claims = Jwts.parser().setSigningKey("liang").parseClaimsJws(token).getBody();
        return claims;
    }



}

你可能感兴趣的:(springboot,java)