Vue+Spring Boot实现token认证

前言
在使用 Vue开发前后分离的项目以前,后台可以通过 Session 储存和获取当前登录的用户信息,进行权限管理。但使用Vue之后,发现虽然前端浏览器没有打开过新的页面。但后台每一次获取请求的Session都不相同。后台无法通过Session辨别当前用户。经过查找资料才发现,如今可以通过token进行身份验证
Vue+Spring Boot实现token认证主要可分为四步
  1. 后台设置拦截器拦截请求,判断请求是否携带token或者判断携带token的权限
  2. 用户登录成功后,后台根据用户信息生成token,并将token的信息封入response
  3. vue收到token后,存入localStorage
  4. axios发送请求时,将token的内容封装到请求

后台配置

创建注解类

package com.booksystem.token;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({
   
   ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserToken {
   
   
    boolean required() default true;
}

maven引入jwt

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

配置拦截器

package com.booksystem.token;

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.booksystem.pojo.User;
import com.booksystem.service.UserService;
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;
import java.lang.reflect.Method;

public class Authentication implements HandlerInterceptor{
   
   
    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
   
   
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值