SpringBoot自定义注解实现Token校验的方法

作者:李秀才 时间:2023-11-13 23:17:52 

1.定义Token的注解,需要Token校验的接口,方法上加上此注解


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Token {
 boolean validate() default true;
}

2.定义LoginUser注解,此注解加在参数上,用在需要从token里获取的用户信息的地方


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

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginUser {
}

3.权限的校验 *


import com.example.demo.annotation.Token;
import com.example.demo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
 public static final String USER_KEY = "USER_ID";
 public static final String USER_INFO = "USER_INFO";
 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
   Token annotation;
   if(handler instanceof HandlerMethod) {
     annotation = ((HandlerMethod) handler).getMethodAnnotation(Token.class);
   }else{
     return true;
   }
   //没有声明需要权限,或者声明不验证权限
   if(annotation == null || annotation.validate() == false){
     return true;
   }
   //从header中获取token
   String token = request.getHeader("token");
   if(token == null){
     log.info("缺少token,拒绝访问");
     return false;
   }

//查询token信息
//    User user = redisUtils.get(USER_INFO+token,User.class);
//    if(user == null){
//      log.info("token不正确,拒绝访问");
//      return false;
//    }

//token校验通过,将用户信息放在request中,供需要用user信息的接口里从token取数据
   request.setAttribute(USER_KEY, "123456");
   User user=new User();
   user.setId(10000L);
   user.setUserName("2118724165@qq.com");
   user.setPhoneNumber("15702911111");
   user.setToken(token);
   request.setAttribute(USER_INFO, user);
   return true;
 }
}

4.写参数的解析器,将登陆用户对象注入到接口里


import com.example.demo.annotation.LoginUser;
import com.example.demo.entity.User;
import com.example.demo.interceptor.AuthorizationInterceptor;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver
{
 @Override
 public boolean supportsParameter(MethodParameter methodParameter) {
   return methodParameter.getParameterType().isAssignableFrom(User.class)&&methodParameter.hasParameterAnnotation(LoginUser.class);
 }

@Override
 public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
   //获取登陆用户信息
   Object object = nativeWebRequest.getAttribute(AuthorizationInterceptor.USER_INFO, RequestAttributes.SCOPE_REQUEST);
   if(object == null){
     return null;
   }
   return (User)object;
 }
}

5.配置 * 和参数解析器


import com.example.demo.interceptor.AuthorizationInterceptor;
import com.example.demo.resolver.LoginUserHandlerMethodArgumentResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
 @Autowired
 private AuthorizationInterceptor authorizationInterceptor;
 @Autowired
 private LoginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver;

@Override
 public void addInterceptors(InterceptorRegistry registry) {
   registry.addInterceptor(authorizationInterceptor).addPathPatterns("/api/**");
 }

@Override
 public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
   argumentResolvers.add(loginUserHandlerMethodArgumentResolver);
 }
}

7.测试类


import com.example.demo.annotation.LoginUser;
import com.example.demo.annotation.Token;
import com.example.demo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api")
@Slf4j
public class TestController {
 @RequestMapping(value="/test",method = RequestMethod.POST)
 @Token
 public String test(@LoginUser User user){
   System.out.println("需要token才可以访问,呵呵……");
   log.info("user:"+user.toString());
   return "test";
 }
 @RequestMapping(value="/noToken",method = RequestMethod.POST)
 public String noToken(){
   System.out.println("不用token就可以访问……");
   return "test";
 }
}

至此,自定义注解实现token校验就大功告成了。

来源:https://blog.csdn.net/qq_33556185/article/details/105420205

标签:SpringBoot,Token,校验
0
投稿

猜你喜欢

  • 在项目中直接使用hystrix的流程分析

    2021-10-22 01:55:21
  • C# 对象持久化详解

    2023-06-24 10:21:47
  • 21天学习android开发教程之SurfaceView与多线程的混搭

    2021-07-22 05:25:09
  • Android自定义view之3D正方体效果实例

    2023-02-01 05:01:34
  • Matlab实现贪吃蛇小游戏的示例代码

    2023-07-14 14:13:00
  • Java线程之守护线程(Daemon)用法实例

    2023-11-29 09:15:13
  • C#实现简单俄罗斯方块

    2023-06-18 07:18:36
  • Springcloud-nacos实现配置和注册中心的方法

    2023-06-15 13:46:42
  • Kotlin类与属性及构造函数的使用详解

    2021-06-04 06:04:20
  • Android使用CrashHandler来获取应用的crash信息的方法

    2023-07-25 20:27:38
  • jdbc与druid连接池的使用详解

    2023-09-18 17:50:11
  • Struts2 Result 参数详解

    2022-04-28 07:54:35
  • Java的Hibernate框架中Criteria查询使用的实例讲解

    2023-08-22 23:25:47
  • java线程池ThreadPoolExecutor的八种拒绝策略示例详解

    2021-06-24 11:31:10
  • Java synchronized轻量级锁的核心原理详解

    2022-10-13 23:28:33
  • Android开发 OpenGL ES绘制3D 图形实例详解

    2023-01-12 00:06:09
  • unity3d发布apk在android虚拟机中运行的详细步骤(unity3d导出android apk)

    2022-11-09 16:18:56
  • java多线程加锁以及Condition类的使用实例解析

    2023-08-07 07:25:30
  • C#实现简单获取及设置Session类

    2021-07-09 06:19:27
  • 关于StringUtils.isBlank()的使用及说明

    2022-06-04 00:52:24
  • asp之家 软件编程 m.aspxhome.com