基于自定义注解实现无需校验权限访问接口

定义自定义注解

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented

public @interface UserLoginIgnore {
    boolean ignore() default true;
}

解读:

  1. @Target({ElementType.METHOD}):用于指定注解的应用目标。在这里,它表示该自定义注解 @UserLoginIgnore只能用于方法上,也就是该注解只能标记方法。

  2. @Retention(RetentionPolicy.RUNTIME):用于指定注解的保留策略。RetentionPolicy.RUNTIME表示该注解会在运行时保留,允许通过反射获取注解信息。

  3. @Documented:这是一个标记注解,它本身不带任何属性,但用于指示编译工具要将注解信息包含在生成的文档中。

  4. boolean ignore() default true;:这是自定义注解的一个属性 ignore,它是一个布尔类型的属性,默认值为 true。在注解中,属性可以用于配置注解的行为。在这个注解中,ignore 属性用于控制是否忽略Token验证,如果 ignore的值为 true,表示忽略Token验证;如果 ignore 的值为 false,表示不忽略Token验证。

添加token拦截器

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //处理跨域问题
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true;
        }
        //拦截Token
        if (handler instanceof HandlerMethod) {
            HandlerMethod h = (HandlerMethod) handler;
            UserLoginIgnore userLoginIgnore = h.getMethodAnnotation(UserLoginIgnore.class);
            //查看是否有@userLoginIgnore注解,若没有该注解或该注解的ignore为false,则需要token校验
            if (userLoginIgnore == null || !userLoginIgnore.ignore()) {
                //Token检验
                //业务代码略
                }
            }
            return true;
        } else {
            response.setStatus(403);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().println(JSONObject.toJSONString(ResultUtil.error(403, "此路径禁止访问!")));
        }
        return false;
    }
}

其中对于拦截token部分,handler是一个方法参数,通常在SpringMVC表示controller的方法,通过方法参数获取注解,若获取到了@UserLoginIgnore注解,且ignore值为true,则进行token校验,否则不进行token校验,直接放行。
别忘了在WebMvcConfig注册拦截器。

registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/api/**");

应用

新建一个ApiController,将对外暴露的接口提取出来,加上@UserLoginIgnore注解即可。

@RestController
@RequestMapping(value = "/api/external", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
public class ApiController {
	 //对外暴露的接口
    @UserLoginIgnore
    @RequestMapping("/test")
    public Result test() {
      		//业务略
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值