jwt令牌生成和解析 + 几种数据获取方法

——————jwt令牌生成和解析

jdk:17

spring boot:3.x

 

JwtUtils.java

其中 String singKey 这一部分不要太短,不然会报错

复制代码
package com.example.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

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

public class JwtUtils {

    private static String singKey = "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhXD";      //签名密钥
    private static Long expire = 43200000L;         //有效期

    /*
    生成令牌
     */
    public static String generateJwt(Map<String, Object> claims){
        String jwt = Jwts.builder()
                .addClaims(claims)      //自定义内容(载荷部分)
                .signWith(SignatureAlgorithm.HS256, singKey)      //设置签名算法
                .setExpiration(new Date(System.currentTimeMillis() + expire))        //有效期
                .compact();
        return jwt;
    }

    /*
    解析(校验)令牌
     */
    public static Claims parseJWT(String jwt){
        Claims claims = Jwts.parser()
                .setSigningKey(singKey)
                .parseClaimsJws(jwt)
                .getBody();     //获得自定义部分内容
        return claims;
    }

}
复制代码

 

使用案例

登录

复制代码
package com.example.controller;

import com.example.pojo.Emp;
import com.example.pojo.Result;
import com.example.service.EmpService;
import com.example.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class LoginController {

    @Autowired
    private EmpService empService;

    @PostMapping("/login")
    public Result login(@RequestBody Emp emp){
        log.info("员工登录,{}",emp);
        Emp e = empService.login(emp);
        //登录成功,生成并下方令牌
        if (e != null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",e.getId());
            claims.put("name",e.getName());
            claims.put("username",e.getUsername());

            //让jwt中包含当前登录的员工信息
            String jwt = JwtUtils.generateJwt(claims);
            return Result.success(jwt);
        }
        //登录失败,返回错误信息
        return Result.error("用户名或密码错误");
    }
}
复制代码

 

解析令牌

复制代码
package com.example.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.pojo.Result;
import com.example.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    /*
    ServletRequest servletRequest:获取请求参数
    ServletResponse servletResponse:响应结果
    FilterChain filterChain:执行放行操作
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取请求url
        String url = request.getRequestURI().toString();
        log.info("请求是url:{}",url);
        //2.判断请求url中是否包含login,如果包含说明是登录操作,放行
        if (url.contains("login")){
            log.info("登录操作,放行……");
            filterChain.doFilter(request,response);
            return;
        }
        //3.获取请求头中的令牌token
        String jwt = request.getHeader("token");
        //4.判断令牌是否存在,如果不存在返回错误结果(未登录)
            //StringUtils.hasLength用于判断字符串是否有长度
        if (!StringUtils.hasLength(jwt)){
            log.info("请求头token为空,返回未登录的信息");
            Result error = Result.error("NOT_LOGIN");
            //手动转换,调用fastJSON将error转换为接送
            String notLogin = JSONObject.toJSONString(error);
            //将未登录结果响应给浏览器
            response.getWriter().write(notLogin);
            return;
        }
        //5.解析token,如果解析失败返回错误结果(未登录)
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            //jwt令牌解析失败
            e.printStackTrace();
            log.info("解析令牌失败,返回未登录的信息");
            Result error = Result.error("NOT_LOGIN");
            //手动转换,调用fastJSON将error转换为接送
            String notLogin = JSONObject.toJSONString(error);
            //将未登录结果响应给浏览器
            response.getWriter().write(notLogin);
            return;
        }
        //6.放行
        log.info("令牌合法,放行");
        filterChain.doFilter(request,response);
    }
}
复制代码

 

——————————————————

几种数据获取方法

复制代码
//操作人的id - 当前登录员工的id
        //获取请求头中的jwt令牌并解析即可
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer operateUser = (Integer) claims.get("id");       //此时拿到了当前登录员工的id
        //操作类名
        //joinPoint.getTarget() 拿到目标对象
        //joinPoint.getTarget().getClass()  拿到类对象
        //joinPoint.getTarget().getClass().getName()    拿到目标类类名
        String className = joinPoint.getTarget().getClass().getName();
        //操作方法名
        //joinPoint.getSignature()  获得方法签名
        String methodName = joinPoint.getSignature().getName();
        //操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);
        //方法返回值
        String returnValue = JSONObject.toJSONString(result);
复制代码

 

posted @   椰子灰  阅读(151)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示