springboot集成JWT验证

springboot集成JWT验证

导入依赖

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

token工具类

package com.example.test.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小时后token过期
                .sign(Algorithm.HMAC256(sign));//以password作为token的密钥
    }
}

JWT拦截器

package com.example.test.common.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.example.test.entity.Admin;
import com.example.test.service.AdminService;
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 AdminService adminService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handle) throws Exception
    {
        String token=request.getHeader("token");
        if(!(handle instanceof HandlerMethod))
        {
            return  true;
        }
        //执行认证
        if(StrUtil.isBlankIfStr(token))
        {
            throw new RuntimeException("无token,请重新登录");
        }
        //获取token中 userId
        String userId;
        try {
            userId= JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException j)
        {
            throw new RuntimeException("token验证失败");
        }
        //根据token中的userId查询数据库
        Admin admin=adminService.getById(userId);
        if(admin==null)
        {
            throw new RuntimeException("用户不存在,请重新登录");
        }
        //用户密码加签验证 token
        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        }catch (JWTVerificationException j)
        {
            throw new RuntimeException("token验证失败,请重新登录");
        }
        return true;

    }

}

拦截器配置

package com.example.test.config;
import com.example.test.common.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("/**").excludePathPatterns("/admin/log","/admin/register","/**/export","/**/import");
    }
    @Bean //Bean注入
    public Jwtinterceptor jwtinterceptor()
    {
        return new Jwtinterceptor();
    }
}

实体类增加字段private String token;

adminController

@PostMapping("/log")
 public Admin login(@RequestBody Admin admin)
{
    QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
    queryWrapper.eq("username",admin.getUsername());
    queryWrapper.eq("password",admin.getPassword());
 
    Admin one= adminService.getOne(queryWrapper);
    String token= TokenUtils.genToken(one.getId().toString(),one.getPassword());
    one.setToken(token);//设置token
    return one;
 }

前端改造

Login.vue

    request.post("/admin/log",this.loginForm).then(res=>{
        console.log(res);
        if(res)
              {//存储请求的res数据
                localStorage.setItem("user",JSON.stringify(res));
               localStorage.setItem("username",this.loginForm.username);
                sessionStorage.setItem("isLogin",'true');
                this.$message.success("登录成功");
                this.$router.push("/");
              }
              else{
                this.$message.error("信息错误");
              }
      })
    }
    else
    {
      this.$message({
        message:"信息错误",
        center:true,
        type: 'error'
      });
    }
  })
},


 

router/index.js

let user=localStorage.getItem("user")
if(user)
{
  console.log("登录成功!")
}
else if(to.path!=="/login"&&to.path!=="/register"&&to.path!=="logout"){
  ElementUI.Message({
    message:"未登录,请登录",
    type:"error",
  })
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值