栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot集成jwt

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot集成jwt

导入依赖

 
        
            com.auth0
            java-jwt
            3.10.3
        

编写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;


@Component
public class TokenUtils {



    private static Users1Service staticUser1Service;

    @Autowired
    private Users1Service users1Service;

    @PostConstruct
    public void setUsers1Service(){
        staticUser1Service=users1Service;
    }
    
    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;



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;
    }

}

配置拦截器,约束拦截规则
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;


@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor())
                .addPathPatterns("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)
});

效果截图

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/770725.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号