首先自定义一个注解
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
-
- /**
- * @Description: token鉴权放行注解
- * @Author: cll
- * @CreateTime: 2023-10-24 20:03
- */
- @Retention(RetentionPolicy.RUNTIME)
- @Target({ElementType.TYPE,ElementType.METHOD})
- public @interface NoAuth {
- }
然后自定义拦截器
- import cn.hutool.core.util.NumberUtil;
- import cn.hutool.core.util.ObjectUtil;
- import cn.hutool.core.util.StrUtil;
- import com.alibaba.fastjson.JSON;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.web.method.HandlerMethod;
- import org.springframework.web.servlet.HandlerInterceptor;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- /**
- * @desc: 登录拦截器
- */
- @Slf4j
- public class LoginInterceptor implements HandlerInterceptor {
-
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- if (HandlerMethod.class.equals(handler.getClass())) {
- HandlerMethod handlerMethod = (HandlerMethod) handler;
- NoAuth noAuth = handlerMethod.getMethod().getAnnotation(NoAuth.class);
- if (noAuth == null) {
- String authorization = request.getHeader("Authorization");
- log.info("登录拦截器authorization:{}", authorization);
-
- if (StringUtils.isBlank(authorization)) {
- log.info("登录拦截器,无权限访问,requestURL:{}", request.getRequestURL());
- throw new ApiException("无权限访问");
- }
- if (StringUtils.isNotBlank(authorization)) {
- //todo 添加token校验逻辑
- }
- }
- }
- return true;
- }
- }
然后注册拦截器
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
- /**
- * @desc:
- * @author:
- * @date:
- */
- @Configuration
- public class MVCConfig implements WebMvcConfigurer {
-
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- registry.addInterceptor(new LoginInterceptor())
- // 拦截路径
- .addPathPatterns("/**")
- // 排除swagger
- .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/api-docs", "/swagger-ui.html/**", "/doc.html", "/favicon.ico")
- ;
- }
- }
- @RestController
- @RequestMapping("/test")
- public class TestController {
- @NoAuth
- @PostMapping("test")
- public String test(){
- return "11111111";
- }
- }