新建注解:

/**
* 想要权限拦截的接口就加上这个注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EnableAuth {
}

编写实现 ApplicationContextAware 的类:

Spring容器已启动就执行 setApplicationContext 方法

/**
* 项目一启动,就调用这个方法获取所有需要权限拦截的接口,放到checkApis中
*/
@Component
@Configuration
public class ApiAuthDataInit implements ApplicationContextAware { /** 存放需要权限拦截的接口uri */
public static List<String> checkApis = new ArrayList<>(); /**
* 获取所有带有@RestController注解的类,
* 并获取该类下所有带有@EnableAuth注解的方法,
* 获取该方法@RequestMapping的uri路径,
* 将uri存入checkApis中
*/
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
Map<String, Object> beanMap = ctx.getBeansWithAnnotation(RestController.class);
if (beanMap != null) {
for (Object bean : beanMap.values()) {
Class<?> clz = bean.getClass();
Method[] methods = clz.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(EnableAuth.class)) {
String uri = getApiUri(clz, method);
System.err.println(uri);
checkApis.add(uri);
}
}
}
}
} private String getApiUri(Class<?> clz, Method method) {
StringBuilder uri = new StringBuilder();
uri.append(clz.getAnnotation(RequestMapping.class).value()[0]);
if (method.isAnnotationPresent(GetMapping.class)) {
uri.append(method.getAnnotation(GetMapping.class).value()[0]);
} else if (method.isAnnotationPresent(PostMapping.class)) {
uri.append(method.getAnnotation(PostMapping.class).value()[0]);
} else if (method.isAnnotationPresent(RequestMapping.class)) {
uri.append(method.getAnnotation(RequestMapping.class).value()[0]);
}
return uri.toString();
} }

编写api拦截器:

package com.tangzhe.filter;

import com.alibaba.fastjson.JSONObject;
import com.tangzhe.util.JWTUtils;
import com.tangzhe.util.LoginInfoUtils;
import org.apache.commons.lang3.StringUtils; import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class ApiFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
resp.setCharacterEncoding("utf-8");
resp.setContentType("application/json;charset=utf-8");
String authorization = req.getHeader("Authorization"); // 判断checkApis中是否包含当前请求的uri
if (ApiAuthDataInit.checkApis.contains(req.getRequestURI())) {
// 获取当前登录用户
String userId = LoginInfoUtils.getLoginUserId(req);
if (userId == null) {
PrintWriter writer = resp.getWriter();
String res = "请先登录";
writer.write(res);
writer.flush();
return;
}
} // 判断token值是否合法
if (StringUtils.isNotBlank(authorization)) {
JWTUtils.JWTResult result = JWTUtils.getInstance().checkToken(authorization);
if (!result.isStatus()) {
// 非法请求
PrintWriter writer = resp.getWriter();
String res = JSONObject.toJSONString(result);
writer.write(res);
writer.flush();
return;
}
} chain.doFilter(request, response);
} public void destroy() { } }

编写测试@EnableAuth 注解的接口:

  @GetMapping("/testEnableAuth")
public String testEnableAuth() {
return "测试权限注解成功";
}

前端项目页面修改:

        <!-- 测试@EnableAuth注解 -->
<div>
<button @click="testEnableAuth">测试EnableAuth注解</button>
</div> ...
testEnableAuth: function() {
axios.get('http://localhost:8889/user/testEnableAuth')
.then(function (response) {
alert(response.data);
})
.catch(function (error) {
console.log(error);
});
}

不打@EnableAuth注解测试:

打上@EnableAuth注解测试:

    @EnableAuth
@GetMapping("/testEnableAuth")
public String testEnableAuth() {
return "测试权限注解成功";
}

会返回 没有登录

需要登录之后,才能请求成功

springboot-vue-自定义注解限制接口调用的更多相关文章

  1. Springboot使用自定义注解实现简单参数加密解密(注解+HandlerMethodArgumentResolver)

    前言 我黄汉三又回来了,快半年没更新博客了,这半年来的经历实属不易,疫情当头,本人实习的公司没有跟员工共患难, 直接辞掉了很多人.作为一个实习生,本人也被无情开除了.所以本人又得重新准备找工作了. 算 ...

  2. SpringBoot:自定义注解实现后台接收Json参数

    0.需求 在实际的开发过程中,服务间调用一般使用Json传参的模式,SpringBoot项目无法使用@RequestParam接收Json传参 只有@RequestBody支持Json,但是每次为了一 ...

  3. Springboot+Redisson自定义注解一次解决重复提交问题(含源码)

    前言   项目中经常会出现重复提交的问题,而接口幂等性也一直以来是做任何项目都要关注的疑难点,网上可以查到非常多的方案,我归纳了几点如下:   1).数据库层面,对责任字段设置唯一索引,这是最直接有效 ...

  4. springboot aop 自定义注解方式实现完善日志记录(完整源码)

    版权声明:本文为博主原创文章,欢迎转载,转载请注明作者.原文超链接 一:功能简介 本文主要记录如何使用aop切面的方式来实现日志记录功能. 主要记录的信息有: 操作人,方法名,参数,运行时间,操作类型 ...

  5. springboot aop 自定义注解方式实现一套完善的日志记录(完整源码)

    https://www.cnblogs.com/wenjunwei/p/9639909.html https://blog.csdn.net/tyrant_800/article/details/78 ...

  6. 使用Redis+自定义注解实现接口防刷

    最近开发了一个功能,需要发送短信验证码鉴权,考虑到短信服务需要收费,因此对此接口做了防刷处理,实现方式主要是Redis+自定义注解(需要导入Redis的相关依赖,完成Redis的相关配置,gs代码,这 ...

  7. springboot使用自定义注解和反射实现一个简单的支付

    优点: 未使用if else,就算以后增加支付类型,也不用改动之前代码 只需要新写一个支付类,给添加自定义注解@Pay 首先: 定义自定义注解 Pay 定义 CMBPay ICBCPay 两种支付 根 ...

  8. springboot aop 自定义注解

    枚举类: /** * Created by tzq on 2018/5/21. */ public enum MyAnnoEnum { SELECT("select"," ...

  9. 基于springboot通过自定义注解和AOP实现权限验证

    一.移入依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spri ...

随机推荐

  1. JsonModel&AFNetWorking

    // HttpManager.h // JsonModel&AFNetWorking // // Created by qianfeng on 15/7/21. // Copyright (c ...

  2. Fleet-运行一个高可用的服务

    运行一个高可用的服务 使用CoreOS最大的好处就是你可以以高可用的方式来运行你的服务.接下来我们将部署两个一样的Apache web server容器.然后,我们将通过让一台机器出现故障,fleet ...

  3. 采用React+Ant Design组件化开发前端界面(一)

    react-start 基础知识 1.使用脚手架创建项目并启动 ​ 1.1 安装脚手架: npm install -g create-react-app ​ 1.2 使用脚手架创建项目: create ...

  4. DOCKER启动失败Job for docker.service failed because the control process exited with error code. See "syste mctl status docker.service" and "journalctl -xe" for details.

    [root@localhost ~]# systemctl start docker Job for docker.service failed because the control process ...

  5. 深入理解Java流机制(一)

    一.前言 C语言本身没有输入输出语句,而是调用"stdio.h"库中的输入输出函数来实现.同样,C++语言本身也没有输入输出,不过有别于C语言,C++有一个面向对象的I/O流类库& ...

  6. Winform中Checkbox与其他集合列表类型之间进行关联

    本文提供了Checkbox与CheckedListBox.DataGridViewCheckBoxColumn等的联动关系 1.CheckboxAssociateFactroy.Create创建联动关 ...

  7. SpringBoot服务监控

    SpringBoot服务监控分为客户端和服务端,即服务端是监控方,客户端为被监控方. 例如需要对线上的SpringBoot服务project-A进行监控,则project-A 为客户端.而监控的服务p ...

  8. 在openSUSE 13.1上用gem安装rails无反应: gem install rails

    解决方案: gem install rails -V ....其实他本身在后台运行,白白的给他中断好多次,用-V这个选项就可以直接回显信息了

  9. poj 3159 Candies (差分约束)

    一个叫差分约束系统的东西.如果每个点定义一个顶标x(v),x(t)-x(s)将对应着s-t的最短路径. 比如说w+a≤b,那么可以画一条a到b的有向边,权值为w,同样地给出b+w2≤c,a+w3≤c. ...

  10. ios常见错误之 Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?

    Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the desi ...