zeromemos
最好的学习方法就是输出所学的知识

JWT(JSON Web Token)工具类的使用

加入依赖

        <!--JDK1.8 jwt依赖-->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

工具类

package com.zeromemos.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtils {

    //有效时长1天
    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    //加密密钥
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHOukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    public static String getJwtToken(String id, String nickname){

        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //设置主题,可自定义
                .setSubject("user_info")
                //有效时间
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                //设置想要的信息
                .claim("id", id)
                .claim("nickname", nickname)
                //加密
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if(StringUtils.isEmpty(jwtToken)) return false;
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token获取会员信息
     * @param jwtToken
     * @return Claims
     */
    public static Claims getMemberByJwtToken(String jwtToken) {
        //解析token
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        //取出内容
        return claimsJws.getBody();
    }
}

直接在测试目录下进行测试

package code;

import com.zeromemos.utils.JwtUtils;
import org.junit.Test;

public class JwtTest {
    @Test
    public void run1(){
        String zero = JwtUtils.getJwtToken("1", "zero");
        System.out.println(zero);
    }

    @Test
    public void run2(){
        System.out.println(JwtUtils.checkToken(""));
    }
}

run1方法进行生成

run2方法进行检查是否有效,如过期

修改run2方法

    @Test
    public void run2(){
        Claims memberByJwtToken = JwtUtils.getMemberByJwtToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyX2luZm8iLCJpYXQiOjE2NzUyNjAwMzQsImV4cCI6MTY3NTM0NjQzNCwiaWQiOiIxIiwibmlja25hbWUiOiJ6ZXJvIn0.6D-Zm5MxrucIgroQbtzOPajKyWo8F6PUMN-xOxbKCx0");
        String nickname = (String)memberByJwtToken.get("nickname");
        System.out.println(memberByJwtToken);
        System.out.println(nickname);
    }

读取存放的信息

评论区

关于我们

本站主要用于记录个人学习笔记,网站开发中,如需以前站内资料请加QQ群272473835索取。注册账号仅提供回帖功能,可不注册!

微信公众号