SpringBoot自定義註解實現Token校驗的方法
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("[email protected]"); 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校驗就大功告成瞭。
到此這篇關於SpringBoot自定義註解實現Token校驗的方法的文章就介紹到這瞭,更多相關SpringBoot Token校驗內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- SpringBoot @ModelAttribute使用場景分析
- SpringBoot自定義註解開發指南
- SpringBoot登錄用戶權限攔截器
- SpringBoot攔截器使用精講
- springboot使用攔截器判斷是否登錄