学做毕设 2022 第十六讲 JWT集成

<!--引入JWT依赖-->
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.10.3</version>
</dependency> 

 utils/生成工具类 tokenUtils
package com.yinming.sprintboot.utils;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import java.util.Date;

public class TokenUtils {
    public static String genToken(String userId,String sign){
      return  JWT.create().withAudience(userId) //将userId保存到token中作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2))//2小时过期
                .sign(Algorithm.HMAC256(sign));//以password为token的密钥        
    }
}
在 UserServiceImpl 中把token中带进
@Override
public UserDto login(UserDto userDto) {
   User one=getUserInfo(userDto);
    if(one!=null)
    {
            BeanUtil.copyProperties(one, userDto,true);
            String token= TokenUtils.genToken(one.getId().toString(),one.getPassword());
            userDto.setToken(token);
            return userDto;
    }else {
        throw new ServiceException("CODE_124","用户名和错误");
    }
}
token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxIiwiZXhwIjoxNjQ1ODgzODc2fQ.6zGYjPqNKf-TH_tME3W42ftr_9j18nap36Ff5fhxurE"
1、头部(header) 声明类型以及加密算法;
2、负载(payload) 携带一些用户身份信息;
3、签名(signature) 签名信息

request.js

// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    let user= localStorage.getItem("user")?JSON.parse(ocalStorage.getItem("user")):{}
    if(user){
        config.headers['token'] = user.token;  // 设置请求头
    } 
    return config

interceptor\JwtInterceptor
package com.yinming.sprintboot.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.yinming.sprintboot.common.Constants;
import com.yinming.sprintboot.entity.User;
import com.yinming.sprintboot.exception.ServiceException;
import com.yinming.sprintboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    private IUserService userService;
    @Autowired
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
    
    // 在请求进入处理器之前回调这个方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("token");
        //如果映身不到方法,直接通过
        if(!(handler instanceof HandlerMethod)){
            return  true;
        }
        //执行认证
        if(StrUtil.isBlank(token)){
            throw new ServiceException(Constants.CODE_400,"当前无token");
        }
        //获取token中的userid
        String userId;
        try {
            userId= JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException j){
            throw new ServiceException(Constants.CODE_400,"TOKEN验证失败");
        }
        User user=userService.getById(userId);
        if(user==null)
        {
            throw new  ServiceException(Constants.CODE_400,"用户不存在");
        }
        //验证token
        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try{
            jwtVerifier.verify(token);
        }catch (JWTVerificationException e){
            throw new  ServiceException(Constants.CODE_400,"token用户不存在");
        }
        return true;
    }
}
InterceptorConfig
package com.yinming.sprintboot.config;
import com.yinming.sprintboot.config.interceptor.JwtInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

    private JwtInterceptor jwtInterceptor;
    @Autowired
    public void setJwtInterceptor(JwtInterceptor jwtInterceptor){
        this.jwtInterceptor = jwtInterceptor;
    }
    // 注册拦截器
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**") //拦截所有请求,来判断是否登录
                .excludePathPatterns("/user/login", "/user/register", "/**/import", "/**/export");
    }
}

utils/ TokenUtils

package com.yinming.sprintboot.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.yinming.sprintboot.entity.User;
import com.yinming.sprintboot.service.IUserService;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class TokenUtils {

    private static IUserService  staticUserService;

    @Resource
    private  static IUserService UserService;
    @PostConstruct
    public  void setUserService(){
        staticUserService=UserService;
    }

    /**
     * 生成token
     * @param userId
     * @param sign
     * @retturn
     */
    public static String genToken(String userId,String sign){
      return  JWT.create().withAudience(userId) //将userId保存到token中作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2))//2小时过期
                .sign(Algorithm.HMAC256(sign));//以password为token的密钥
    }

    public static User getCurrentUser(){
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
           String token=request.getHeader("token");
           if(StrUtil.isNotBlank(token)){
               String userId=JWT.decode(token).getAudience().get(0);
               return staticUserService.getById(Integer.valueOf(userId));
           }
        }catch (Exception e)
        {
            return null;
        }
        return  null;
    }

Controller.里面调用 

User user=TokenUtils.getCurrentUser();
System.out.println(user.getUsername());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值