springboot-vue-自定义注解限制接口调用
新建注解:
/**
* 想要权限拦截的接口就加上这个注解
*/
@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-自定义注解限制接口调用的更多相关文章
- Springboot使用自定义注解实现简单参数加密解密(注解+HandlerMethodArgumentResolver)
前言 我黄汉三又回来了,快半年没更新博客了,这半年来的经历实属不易,疫情当头,本人实习的公司没有跟员工共患难, 直接辞掉了很多人.作为一个实习生,本人也被无情开除了.所以本人又得重新准备找工作了. 算 ...
- SpringBoot:自定义注解实现后台接收Json参数
0.需求 在实际的开发过程中,服务间调用一般使用Json传参的模式,SpringBoot项目无法使用@RequestParam接收Json传参 只有@RequestBody支持Json,但是每次为了一 ...
- Springboot+Redisson自定义注解一次解决重复提交问题(含源码)
前言 项目中经常会出现重复提交的问题,而接口幂等性也一直以来是做任何项目都要关注的疑难点,网上可以查到非常多的方案,我归纳了几点如下: 1).数据库层面,对责任字段设置唯一索引,这是最直接有效 ...
- springboot aop 自定义注解方式实现完善日志记录(完整源码)
版权声明:本文为博主原创文章,欢迎转载,转载请注明作者.原文超链接 一:功能简介 本文主要记录如何使用aop切面的方式来实现日志记录功能. 主要记录的信息有: 操作人,方法名,参数,运行时间,操作类型 ...
- springboot aop 自定义注解方式实现一套完善的日志记录(完整源码)
https://www.cnblogs.com/wenjunwei/p/9639909.html https://blog.csdn.net/tyrant_800/article/details/78 ...
- 使用Redis+自定义注解实现接口防刷
最近开发了一个功能,需要发送短信验证码鉴权,考虑到短信服务需要收费,因此对此接口做了防刷处理,实现方式主要是Redis+自定义注解(需要导入Redis的相关依赖,完成Redis的相关配置,gs代码,这 ...
- springboot使用自定义注解和反射实现一个简单的支付
优点: 未使用if else,就算以后增加支付类型,也不用改动之前代码 只需要新写一个支付类,给添加自定义注解@Pay 首先: 定义自定义注解 Pay 定义 CMBPay ICBCPay 两种支付 根 ...
- springboot aop 自定义注解
枚举类: /** * Created by tzq on 2018/5/21. */ public enum MyAnnoEnum { SELECT("select"," ...
- 基于springboot通过自定义注解和AOP实现权限验证
一.移入依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spri ...
随机推荐
- FirstAFNetWorking
// ViewController.h // FirstAFNetWorking // // Created by 张国锋 on 15/7/20. // Copyright (c) 2015年 张国锋 ...
- 【Linux】Ubuntu配置zshell&oh-my-zsh
zshell:https://archive.codeplex.com/?p=shell oh-my-zsh: https://github.com/robbyrussell/oh-my-zsh 终极 ...
- go语言简单的soap调用方法
package main import ( "bytes" "encoding/xml" "fmt" "io" &quo ...
- 【css】css2实现两列三列布局的方法
前言 对于 flex 弹性布局相信大家都有所了解,它是 css3 中的属性,然而它具有一定的兼容性问题.楼主前几天面试时遇到了面试官需要设计一个两列布局,我当然就说父元素 flex 吧哩吧啦,然而需要 ...
- Eucalyptus——EC2的开源实现(转载)
Eucalyptus[22]是加利福尼亚大学的 Daniel Nurmi 等人实现的,是一个用于实现云计算的开源软件基础设施.Eucalyptus 是 Amazon EC2 的一个开源实现,它与 EC ...
- hd - MFM/IDE 硬盘设备
描述 DESCRIPTION hd* 开头的设备是以裸模式(raw mode)访问MFM/IDE类型硬盘的块设备. 第一个IDE驱动控制器上的主盘(主设备号3)是 hda ;从盘是 hdb. 第二个I ...
- linux文本处理工具及正则表达式
cat命令:查看文本内容 cat [选项]... [文件]... -E 显示行结束符 -n 显示文本内容时显示行号 -A 显示所以控制符 -b 非空行编号 -s 压缩连 ...
- C#语言命名的9种规范
下面介绍C#语言命名的9种规范: a) 类 [规则1-1]使用Pascal规则命名类名,即首字母要大写. [规则1-2]使用能够反映类功能的名词或名词短语命名类. [规则1-3]不要使用“I”.“C” ...
- The expected type was 'System.Int64' but the actual value was null.”
System.InvalidOperationException:“An exception occurred while reading a database value for property ...
- Java开发小游戏 用键盘控制精灵在游戏中上下左右跑动 窗体小游戏可打包下载,解压后双击start运行
package com.swift; import java.awt.Point; import java.awt.event.KeyEvent; import com.rupeng.game.Gam ...