前段时间写过一篇关于自定义拦截器实现权限过滤的文章,当时是用了自定义mybatis拦截器实现的:SpringBoot自定义Mybatis拦截器实现扩展功能(比如数据权限控制)。最近学习设计模式发现可以用责任链模式实现权限过滤,因此本篇采用责任链模式设计实现权限功能,算是抛砖引玉吧!
权限过滤功能基于责任链模式
前言
项目采用Spring Boot 2.7.12 + JDK 8实现,权限认证就是一个拦截的过程,所以在实现的时候理论上可以做到任意的配置,对任意接口设置任意规则。考虑到鉴权是一系列顺序执行,所以使用了责任链模式进行设计和实现。
一、项目整体架构

项目下载地址,欢迎各位靓仔靓妹Star哦~~
permission
二、项目介绍
1.权限注解及权限处理器
Authority注解用于对controller层设置不同的读写类型
/**
* 权限注解
*
* @author huahua
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Authority {
/**
* 方法描述
*/
String description();
/**
* 权限名称
*/
String permissionName() default "";
/**
* 权限类型,1读,2读写
*/
int type() default 1;
/**
* 不允许访问的用户id
*/
int notAllow() default 0;
}
AuthorityBeanPostProcess
/**
* 权限处理器
*
* @author huahua
*/
@Component
public class AuthorityBeanPostProcess implements BeanPostProcessor {
public static Map<String,Authority> map = new HashMap();
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Class<?> aClass = bean.getClass();
Method[] declaredMethods = aClass.getDeclaredMethods();
for (Method method : declaredMethods) {
if (method.isAnnotationPresent(Authority.class)) {
String name = method.getName();
Authority annotation = method.getAnnotation(Authority.class);
map.put(name,annotation);
}
}
return bean;
}
}
2.自定义权限拦截器
AuthorityInterceptor
在springBoot项目启动时,把所有被@Authority注解注释的方法筛选出来,并且放入缓存中(这里直接放到了map中)备用。这里也可以将方法存入数据库中,字段就是权限的各种拦截方式,可以根据需要自己调整,并且配合责任链模式,扩展、调整都很方便。
/**
* 自定义的权限拦截器
*
* @author huahua
*/
@Component
public class AuthorityInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
String name = handlerMethod.getMethod().getName();
//拦截器想要获取容器中bean需要拿到bean工厂进行getBean()
BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
AuthorityHandlerProcess authorityProcess = factory.getBean("authorityProcess", AuthorityHandlerProcess.class);
//从redis或者缓存中取得方法与权限关系
Authority authority = AuthorityBeanPostProcess.map.get(name);
if (authority != null) {
//对当前用户进行权限校验
//实际场景中,需要根据当前登录用户身份从数据库中查询其权限角色信息
//获取用户信息。因为用户已经登录了,那么user的信息是保存在我们的缓存里的,token获取,这里写一个假数据。
User user = new User();
//模拟一个用户,设置其权限类型,1读,2读写
user.setAuthority(1);
user.setId(1);
try {
//责任链调用,可以动态配置调用规则,即权限校验规则,
authorityProcess.process(user, authority);
} catch
使用责任链模式实现SpringBoot权限过滤

本文介绍了如何使用责任链模式设计和实现权限过滤功能,通过自定义的Mybatis拦截器和一系列权限处理器,实现对Controller层方法的权限注解和校验。项目中包含了权限注解、权限拦截器、抽象权限处理类以及统一响应结果和异常处理。测试部分展示了不同权限用户对查询和删除操作的访问情况。
最低0.47元/天 解锁文章
5907

被折叠的 条评论
为什么被折叠?



