SpringBoot自定义注解实现Token校验的方法
1.定义Token的注解,需要Token校验的接口,方法上加上此注解
importjava.lang.annotation.ElementType; importjava.lang.annotation.Retention; importjava.lang.annotation.RetentionPolicy; importjava.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public@interfaceToken{ booleanvalidate()defaulttrue; }
2.定义LoginUser注解,此注解加在参数上,用在需要从token里获取的用户信息的地方
importjava.lang.annotation.ElementType; importjava.lang.annotation.Retention; importjava.lang.annotation.RetentionPolicy; importjava.lang.annotation.Target; @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public@interfaceLoginUser{ }
3.权限的校验拦截器
importcom.example.demo.annotation.Token; importcom.example.demo.entity.User; importlombok.extern.slf4j.Slf4j; importorg.springframework.stereotype.Component; importorg.springframework.web.method.HandlerMethod; importorg.springframework.web.servlet.handler.HandlerInterceptorAdapter; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; @Component @Slf4j publicclassAuthorizationInterceptorextendsHandlerInterceptorAdapter{ publicstaticfinalStringUSER_KEY="USER_ID"; publicstaticfinalStringUSER_INFO="USER_INFO"; @Override publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{ Tokenannotation; if(handlerinstanceofHandlerMethod){ annotation=((HandlerMethod)handler).getMethodAnnotation(Token.class); }else{ returntrue; } //没有声明需要权限,或者声明不验证权限 if(annotation==null||annotation.validate()==false){ returntrue; } //从header中获取token Stringtoken=request.getHeader("token"); if(token==null){ log.info("缺少token,拒绝访问"); returnfalse; } //查询token信息 //Useruser=redisUtils.get(USER_INFO+token,User.class); //if(user==null){ //log.info("token不正确,拒绝访问"); //returnfalse; //} //token校验通过,将用户信息放在request中,供需要用user信息的接口里从token取数据 request.setAttribute(USER_KEY,"123456"); Useruser=newUser(); user.setId(10000L); user.setUserName("2118724165@qq.com"); user.setPhoneNumber("15702911111"); user.setToken(token); request.setAttribute(USER_INFO,user); returntrue; } }
4.写参数的解析器,将登陆用户对象注入到接口里
importcom.example.demo.annotation.LoginUser; importcom.example.demo.entity.User; importcom.example.demo.interceptor.AuthorizationInterceptor; importorg.springframework.core.MethodParameter; importorg.springframework.stereotype.Component; importorg.springframework.web.bind.support.WebDataBinderFactory; importorg.springframework.web.context.request.NativeWebRequest; importorg.springframework.web.context.request.RequestAttributes; importorg.springframework.web.method.support.HandlerMethodArgumentResolver; importorg.springframework.web.method.support.ModelAndViewContainer; @Component publicclassLoginUserHandlerMethodArgumentResolverimplementsHandlerMethodArgumentResolver { @Override publicbooleansupportsParameter(MethodParametermethodParameter){ returnmethodParameter.getParameterType().isAssignableFrom(User.class)&&methodParameter.hasParameterAnnotation(LoginUser.class); } @Override publicObjectresolveArgument(MethodParametermethodParameter,ModelAndViewContainermodelAndViewContainer,NativeWebRequestnativeWebRequest,WebDataBinderFactorywebDataBinderFactory)throwsException{ //获取登陆用户信息 Objectobject=nativeWebRequest.getAttribute(AuthorizationInterceptor.USER_INFO,RequestAttributes.SCOPE_REQUEST); if(object==null){ returnnull; } return(User)object; } }
5.配置拦截器和参数解析器
importcom.example.demo.interceptor.AuthorizationInterceptor; importcom.example.demo.resolver.LoginUserHandlerMethodArgumentResolver; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.context.annotation.Configuration; importorg.springframework.web.method.support.HandlerMethodArgumentResolver; importorg.springframework.web.servlet.config.annotation.InterceptorRegistry; importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer; importjava.util.List; @Configuration publicclassWebMvcConfigimplementsWebMvcConfigurer{ @Autowired privateAuthorizationInterceptorauthorizationInterceptor; @Autowired privateLoginUserHandlerMethodArgumentResolverloginUserHandlerMethodArgumentResolver; @Override publicvoidaddInterceptors(InterceptorRegistryregistry){ registry.addInterceptor(authorizationInterceptor).addPathPatterns("/api/**"); } @Override publicvoidaddArgumentResolvers(ListargumentResolvers){ argumentResolvers.add(loginUserHandlerMethodArgumentResolver); } }
7.测试类
importcom.example.demo.annotation.LoginUser; importcom.example.demo.annotation.Token; importcom.example.demo.entity.User; importlombok.extern.slf4j.Slf4j; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RequestMethod; importorg.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value="/api") @Slf4j publicclassTestController{ @RequestMapping(value="/test",method=RequestMethod.POST) @Token publicStringtest(@LoginUserUseruser){ System.out.println("需要token才可以访问,呵呵……"); log.info("user:"+user.toString()); return"test"; } @RequestMapping(value="/noToken",method=RequestMethod.POST) publicStringnoToken(){ System.out.println("不用token就可以访问……"); return"test"; } }
至此,自定义注解实现token校验就大功告成了。
到此这篇关于SpringBoot自定义注解实现Token校验的方法的文章就介绍到这了,更多相关SpringBootToken校验内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。