【无标题】# SpringBoot+vue+Jwt实现token验证

SpringBoot+vue+Jwt实现token验证

第一步:导入Jwt依赖


        <dependency>
            <groupId>com.auth0groupId>
            <artifactId>java-jwtartifactId>
            <version>4.0.0version>
        dependency>

第二步:实现一个拦截器,以此来获取前端传输过来的token、查询数据库中以token对应的用户

package com.kingback.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.kingback.common.Constants;
import com.kingback.entity.User;
import com.kingback.exception.ServiceException;
import com.kingback.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
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
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");//此处收到前端发送的token
//        System.out.println("@@@@@@@@@@@@@@@@@@@token的值为"+token);
        //如果不是映射到方法就直接通过
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        //执行认证
        if (StrUtil.isBlank(token)){
            throw new ServiceException(Constants.CODE_401,"无token,请重新登录");
        }
        //获取token中的userid
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException j){
            throw new ServiceException(Constants.CODE_401,"token验证失败");
        }
        //根据token中的userid查询数据库
        User user = userService.findById(Integer.parseInt(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,"token验证失败");
        }
        return true;
    }
}

第三步:设置要具体拦截的方法以及要放行的方法

package com.kingback.config;

import com.kingback.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("/**")//拦截所有请求,通过判断token是否合法来决定是否需要登录
               .excludePathPatterns("/user/login","/user/register","/file/**");
    }
    @Bean
    public JwtInterceptor jwtInterceptor(){
        return new JwtInterceptor();
    }
}

第四步获取用户信息:

package com.kingback.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.kingback.entity.User;
import com.kingback.service.IUserService;
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.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/***
 * 生成token
 */
@Component
public class TokenUtils {
    private static IUserService staticUserServie;
    @Resource
    private IUserService userService;
    @PostConstruct
    public void setUserService(){
        staticUserServie =userService;
    }


    public static String getToken(String userId,String sign){
       return JWT.create().withAudience(userId)//将userId保存到token里面,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),2))//2小时tiken过期
                .sign(Algorithm.HMAC256(sign)); //以password作为token的密钥
    }
    /**
     * 获取当前登录的用户信息
     * @return
     */
    public static User getCurrentUser(){
        //拿到token
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            System.out.println("#############"+token);
            if (!StrUtil.isBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                System.out.println("userId"+userId);
                return staticUserServie.findById(Integer.valueOf(userId));
            }
        }catch (Exception e){
            return null;
        }
        return null;
    }
}

第五步:在登录方法中设置token

你可能感兴趣的:(前端,spring,boot)