Springboot集成jwt

导入依赖

 <!--jwt-->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.10.3</version>
        </dependency>

编写jwt工具类
TokenUtils.java

package com.chen.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.chen.pojo.Users;
import com.chen.service.Users1Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

/**
 * @date 2022/3/11 11:39
 */
@Component
public class TokenUtils {



    private static Users1Service staticUser1Service;

    @Autowired
    private Users1Service users1Service;

    @PostConstruct
    public void setUsers1Service(){
        staticUser1Service=users1Service;
    }
    /**
     * 生成token
     * @return
     */
    public static String genToken(String userId,String sign){
      return   JWT.create().withAudience(userId) // 将 user id 作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2)) //2小时后token过期
                .sign(Algorithm.HMAC256(sign));
    }

//获取当前用户
public static Users 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 staticUser1Service.getById(Integer.valueOf(userId));
        }
    } catch (Exception e) {
        return null;
    }
    return null;
}
}

自定义异常
JwtInterceptor .java

package com.chen.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.chen.common.Constants;
import com.chen.exception.ServiceException;
import com.chen.pojo.Users;
import com.chen.service.Impl.Users1ServiceImpl;
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;

/**
 * @date 2022/3/12 21:16
 */

public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    Users1ServiceImpl users1Service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过

        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //执行认证
        if (StrUtil.isBlank(token)){
            throw new ServiceException(Constants.CODE_401,"无token,请登录");
        }
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new ServiceException(Constants.CODE_401,"token验证失败");

        }

        Users user = users1Service.getById(userId);
        if (user == null) {
            throw new ServiceException(Constants.CODE_401,"用户不存在,请重新登录");
        }

        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException(Constants.CODE_401,"用户不存在,请重新登录");
        }
        return true;
    }

}

ServiceException

package com.chen.exception;
import lombok.Getter;
/**
 * @author chen
 * @date 2022/3/6 13:54
 */


/**
 * 自定义异常  运行时异常
 */
@Getter
@SuppressWarnings("all")
public class ServiceException extends RuntimeException {

    private String code;

    public ServiceException(String code, String msg) {
        super(msg);
        this.code = code;
    }

}


GlobalExceptionHandler

package com.chen.exception;

import com.chen.common.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author chen
 * @date 2022/3/6 13:51
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * @ExceptionHandler相当于controller的@RequestMapping
     * 如果抛出的的是ServiceException,则调用该方法
     * @param se 业务异常
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Result handle(ServiceException se){
        return Result.error(se.getCode(),se.getMessage());
    }
}


配置拦截器,约束拦截规则
InterceptorConfig .java

package com.chen.config;

import com.chen.config.interceptor.JwtInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @date 2022/3/12 21:02
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor())
                .addPathPatterns("/**")  //拦截所有请求,通过判断token是佛合法来判断是否需要登录
                .excludePathPatterns("/sys/login","/sys/register","/**/export","/**/import");   //排除规则
    }

    @Bean
    public JwtInterceptor  jwtInterceptor(){
        return new JwtInterceptor();
    }
}

最后调用方法获取当前用户

//        获取当前用户信息
        Users currentUser = TokenUtils.getCurrentUser();

        System.out.println(currentUser.getNickname());

将token放在前端请求中

request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    //获取用户  判断有没有用户登录
    let user=localStorage.getItem("user")?JSON.parse(localStorage.getItem("user")):{}
    if (user) {
        config.headers['token'] = user.token;  // 设置请求头
    }


    return config
}, error => {
    return Promise.reject(error)
});

在这里插入图片描述

效果截图
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值