SpringBoot登录验证token拦截器的实现

2022-11-13 11:11:06 登录 拦截器 验证

用户访问接口验证,如果用户没有登录,则不让他访问除登录外的任何接口。

实现思路:

1.前端登录,后端创建token(通过Jwt这个依赖),返给前端

2.前端访问其他接口,传递token,后端判断token存在以或失效

3.失效或不存在,则返回失效提示,前端根据接口返回的失效提示,让其跳转到登录界面

注解定义

定义2个注解,1个用于任何接口都能访问,另外一个用于需要登录才能访问

调用都通过注解

package com.example.etf.story.tools;
 
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 PassToken {
    boolean required() default true;
}

登录才能通过

package com.example.etf.story.tools;
 
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 UserLoginToken {
    boolean required() default true;
}

注解的作用说明

@Target代表此注解,能@到哪些代码上

@Target:注解的作用目标

  • @Target(ElementType.TYPE)——接口、类、枚举、注解
  • @Target(ElementType.FIELD)——字段、枚举的常量
  • @Target(ElementType.METHOD)——方法
  • @Target(ElementType.PARAMETER)——方法参数
  • @Target(ElementType.CONSTRUCTOR) ——构造函数
  • @Target(ElementType.LOCAL_VARIABLE)——局部变量
  • @Target(ElementType.ANNOTATION_TYPE)——注解
  • @Target(ElementType.PACKAGE)——包

@Retention:注解的保留位置

  • RetentionPolicy.SOURCE:这种类型的Annotations只在源代码级别保留,编译时就会被忽略,在class字节码文件中不包含。
  • RetentionPolicy.CLASS:这种类型的Annotations编译时被保留,默认的保留策略,在class文件中存在,但JVM将会忽略,运行时无法获得。
  • RetentionPolicy.RUNTIME:这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用。
  • @Document:说明该注解将被包含在javadoc
  • @Inherited:说明子类可以继承父类中的该注解

token生成与验证

传送门

然后SpringBoot拦截器验证token

拦截器定义

拦截器配置定义

拦截器拦截,除了登录和发送短信,不拦截,其他都拦截

package com.example.etf.story.tools;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.WEB.servlet.config.annotation.InterceptorReGIStry;
import org.springframework.web.servlet.config.annotation.WebmvcConfigurer;
 
import javax.annotation.Resource;
 
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Resource
    private LoginInterceptor loginInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册自己的拦截器,并设置拦截的请求路径
        //addPathPatterns为拦截此请求路径的请求
        //excludePathPatterns为不拦截此路径的请求
        registry.addInterceptor(loginInterceptor).addPathPatterns("/story
    @Resource
    private TestClientService testClientService;
 
    @Override
    public boolean preHandle(httpservletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
 
        //检查方法是否有passtoken注解,有则跳过认证,直接通过
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new RuntimeException("无token,请重新登录");
                }
                // 获取 token 中的 user id
                String phone;
                try {
                    phone = JWT.decode(token).getClaim("phone").asString();
                } catch (JWTDecodeException j) {
                    throw new RuntimeException("token不正确,请不要通过非法手段创建token");
                }
                //查询数据库,看看是否存在此用户,方法要自己写
                UserInfoParam userInfoParam = testClientService.selectUserByPhone(phone);
                if (userInfoParam == null) {
                    throw new RuntimeException("用户不存在,请重新登录");
                }
 
                // 验证 token
                if (TokenUtils.verify(token)) {
                    return true;
                } else {
                    throw new RuntimeException("token过期或不正确,请重新登录");
                }
 
            }
        }
          throw new RuntimeException("没有权限注解一律不通过");
    }
 
 
 
 
        
        @Override
        public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
        modelAndView) throws Exception {
            System.out.println("postHandle执行{}");
 
        }
        
        @Override
        public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception
        ex) throws Exception {
            System.out.println("afterCompletion执行异常");
 
        }
 
}

注解使用

在controller层加入注解进行测试

返回值-全局异常类定义

加入全局,异常类,这样当异常,会返回你所指定的异常

package com.example.etf.story.tools;
 
import com.alibaba.fastJSON.jsONObject;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
 
 
@ControllerAdvice
public class GloablExceptionHandler {
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e) {
        String msg = e.getMessage();
        if (msg == null || msg.equals("")) {
            msg = "服务器出错";
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", msg);
        jsonObject.put("status",500)
        return jsonObject;
    }
}

各种测试

不传token

成功

制造可行的假token

我们测试一下加token后的

 因为数据库里,我没有插入,所以不存在,我们在随便写个token

伪造token测试

我们在试试

程序员使用:方法不加注解,测试

程序员使用:加上,调用通过,注解

 我们试试,加上通过注解

拓展:从请求中获取token

我们在试试从中获取token

参考文章:

SpringBoot集成JWT实现token验证 - 简书

springboot对请求的接口实现token拦截以及参数校验_kotomeli的博客-CSDN博客_springboot拦截请求参数

到此这篇关于SpringBoot登录验证token拦截器的实现的文章就介绍到这了,更多相关SpringBoot token拦截器内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章