您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在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("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"; } }
上述內容就是怎么在SpringBoot中通過自定義注解實現一個Token校驗功能,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。