jjwt 生成token

实现原理

在这里插入图片描述

导入maven依赖

<dependency>
      <groupId>io.jsonwebtoken</groupId>
      <artifactId>jjwt</artifactId>
      <version>0.9.0</version>
  </dependency>

创建实体对象

package com.wl.study.utils;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SessionInfo {

    private Long userId;

    private String userName;


    private String token;
}

创建token生成与解析

package com.wl.study.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
import java.util.Optional;

public class JwtUtil {


    /***
     * 生成token
     * @param sessionInfo
     * @return
     */
    public static Optional<String> generateToken(SessionInfo sessionInfo){

        String token = Jwts.builder()
                //主题
                .setSubject(JwtConfig.JWT_SUBJECT)
                //自定义属性
                .claim(JwtConfig.JWT_USERID, sessionInfo.getUserId())
                .claim(JwtConfig.JWT_USERNAME, sessionInfo.getUserName())
                // 压缩
                .compressWith(CompressionCodecs.DEFLATE)
                // 签名
                .signWith(SignatureAlgorithm.HS512, JwtConfig.JWT_SIGNING_KEY)
                .compact();
        return Optional.of(MessageFormat.format("{0}{1}",JwtConfig.JWT_TOKEN_PREFIX,token));
    }


    /***
     * 解析token
     * @param token
     * @return
     */
    public static Optional<SessionInfo> parserToken(String token){

        if(StringUtils.isEmpty(token)){
           return Optional.empty();
        }

        Claims claims = Jwts.parser()
                .setSigningKey(JwtConfig.JWT_SIGNING_KEY)
                .parseClaimsJws(token.replace(JwtConfig.JWT_TOKEN_PREFIX, ""))
                .getBody();

        SessionInfo sessionInfo = SessionInfo.builder().token(token).build();
        if(claims.containsKey(JwtConfig.JWT_USERID)){
            sessionInfo.setUserId( Long.valueOf(claims.get(JwtConfig.JWT_USERID).toString()));
        }
        if(claims.containsKey(JwtConfig.JWT_USERNAME)){
            sessionInfo.setUserName( claims.get(JwtConfig.JWT_USERNAME).toString());
        }

        return Optional.of(sessionInfo);
    }

    private static class JwtConfig{

        private final static String JWT_SUBJECT ="integral";

        private final static String JWT_USERID ="userId";

        private final static String JWT_USERNAME ="userName";

        /***
         * 密钥
         */
        private final static String JWT_SIGNING_KEY = "integral@Jwt!&key^#";

        /**
         * jwt的前缀
         */
        public static final String JWT_TOKEN_PREFIX = "Bearer ";

    }

    public static void main(String[] args) {

        SessionInfo sessionInfo = new SessionInfo();
        sessionInfo.setUserId(1L);
        sessionInfo.setUserName("张飞");
        Optional<String> optional = JwtUtil.generateToken(sessionInfo);
        System.out.println(MessageFormat.format("{0}:{1}","生成token",optional.orElse(null)));

        System.out.println(MessageFormat.format("{0}:{1}","解析token",JwtUtil.parserToken(optional.get())));
    }
}

创建token工具类

package com.wl.study.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
import java.util.Optional;

public class JwtUtil {


    /***
     * 生成token
     * @param sessionInfo
     * @return
     */
    public static Optional<String> generateToken(SessionInfo sessionInfo){

        String token = Jwts.builder()
                //主题
                .setSubject(JwtConfig.JWT_SUBJECT)
                //自定义属性
                .claim(JwtConfig.JWT_USERID, sessionInfo.getUserId())
                .claim(JwtConfig.JWT_USERNAME, sessionInfo.getUserName())
                // 压缩
                .compressWith(CompressionCodecs.DEFLATE)
                // 签名
                .signWith(SignatureAlgorithm.HS512, JwtConfig.JWT_SIGNING_KEY)
                .compact();
        return Optional.of(MessageFormat.format("{0}{1}",JwtConfig.JWT_TOKEN_PREFIX,token));
    }


    /***
     * 解析token
     * @param token
     * @return
     */
    public static Optional<SessionInfo> parserToken(String token){

        if(StringUtils.isEmpty(token)){
           return Optional.empty();
        }

        Claims claims = Jwts.parser()
                .setSigningKey(JwtConfig.JWT_SIGNING_KEY)
                .parseClaimsJws(token.replace(JwtConfig.JWT_TOKEN_PREFIX, ""))
                .getBody();

        SessionInfo sessionInfo = SessionInfo.builder().token(token).build();
        if(claims.containsKey(JwtConfig.JWT_USERID)){
            sessionInfo.setUserId( Long.valueOf(claims.get(JwtConfig.JWT_USERID).toString()));
        }
        if(claims.containsKey(JwtConfig.JWT_USERNAME)){
            sessionInfo.setUserName( claims.get(JwtConfig.JWT_USERNAME).toString());
        }

        return Optional.of(sessionInfo);
    }

    private static class JwtConfig{

        private final static String JWT_SUBJECT ="integral";

        private final static String JWT_USERID ="userId";

        private final static String JWT_USERNAME ="userName";

        /***
         * 密钥
         */
        private final static String JWT_SIGNING_KEY = "integral@Jwt!&key^#";

        /**
         * jwt的前缀
         */
        public static final String JWT_TOKEN_PREFIX = "Bearer ";

    }

    public static void main(String[] args) {

        SessionInfo sessionInfo = new SessionInfo();
        sessionInfo.setUserId(1L);
        sessionInfo.setUserName("张飞");
        Optional<String> optional = JwtUtil.generateToken(sessionInfo);
        System.out.println(MessageFormat.format("{0}:{1}","生成token",optional.orElse(null)));

        System.out.println(MessageFormat.format("{0}:{1}","解析token",JwtUtil.parserToken(optional.get())));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值