自定义Shiro注解

自定义Shiro注解

顺序

  1. 创建自定义的注解
  2. 资源管理器,继承AuthorizationAttributeSourceAdvisor,添加新注解支持
  3. AOP拦截器,继承AopAllianceAnnotationsAuthorizingMethodInterceptor
  4. 方法拦截器,继承AuthorizingAnnotationMethodInterceptor
  5. 权限处理器,继承AuthorizingAnnotationHandler,校验权限

一、自定义注解

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Permissions {
  String[] value();
}

二、权限处理器

import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.aop.AuthorizingAnnotationHandler;
import org.apache.shiro.subject.Subject;

import java.lang.annotation.Annotation;

/**
 * 自定义权限处理器
 * @author BBF
 */
public class PermissionHandler extends AuthorizingAnnotationHandler {

  public PermissionHandler() {
    super(Permissions.class);
  }

  @Override
  public void assertAuthorized(Annotation a) throws AuthorizationException {
    if (a instanceof Permissions) {
      Permissions annotation = (Permissions) a;
      String[] perms = annotation.value();
      Subject subject = getSubject();

      if (perms.length == 1) {
        subject.checkPermission(perms[0]);
        return;
      }
      // 多个权限,有一个就通过
      boolean hasAtLeastOnePermission = false;
      for (String permission : perms) {
        if (subject.isPermitted(permission)) {
          hasAtLeastOnePermission = true;
          break;
        }
      }
      // Cause the exception if none of the role match,
      // note that the exception message will be a bit misleading
      if (!hasAtLeastOnePermission) {
        subject.checkPermission(perms[0]);
      }
    }
  }
}

三、方法拦截器

import org.apache.shiro.aop.AnnotationResolver;
import org.apache.shiro.aop.MethodInvocation;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.aop.AuthorizingAnnotationMethodInterceptor;

/**
 * 自定义注解的方法拦截器
 * @author BBF
 */
public class PermissionMethodInterceptor extends AuthorizingAnnotationMethodInterceptor {
  public PermissionMethodInterceptor() {
    super(new PermissionHandler());
  }

  public PermissionMethodInterceptor(AnnotationResolver resolver) {
    super(new PermissionHandler(), resolver);
  }

  @Override
  public void assertAuthorized(MethodInvocation mi) throws AuthorizationException {
    // 验证权限
    try {
      ((PermissionHandler) getHandler()).assertAuthorized(getAnnotation(mi));
    } catch (AuthorizationException ae) {
      // Annotation handler doesn't know why it was called, so add the information here if possible.
      // Don't wrap the exception here since we don't want to mask the specific exception, such as
      // UnauthenticatedException etc.
      if (ae.getCause() == null) {
        ae.initCause(new AuthorizationException("Not authorized to invoke method: " + mi.getMethod()));
      }
      throw ae;
    }
  }
}

四、切面拦截器

import org.apache.shiro.spring.aop.SpringAnnotationResolver;
import org.apache.shiro.spring.security.interceptor.AopAllianceAnnotationsAuthorizingMethodInterceptor;

/**
 * 自定义注解的AOP拦截器
 * @author BBF
 */
public class PermissionAopInterceptor extends AopAllianceAnnotationsAuthorizingMethodInterceptor {
  public PermissionAopInterceptor() {
    super();
    // 添加自定义的注解拦截器
    this.methodInterceptors.add(new PermissionMethodInterceptor(new SpringAnnotationResolver()));
  }
}

五、注解拦截器

import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.Method;

/**
 * 自定义的Shiro注解拦截器
 * @author BBF
 */

public class ShiroAdvisor extends AuthorizationAttributeSourceAdvisor {
  /**
   * Create a new AuthorizationAttributeSourceAdvisor.
   */
  public ShiroAdvisor() {
    // 这里可以添加多个
    setAdvice(new PermissionAopInterceptor());
  }

  @SuppressWarnings({"unchecked"})
  @Override
  public boolean matches(Method method, Class targetClass) {
    Method m = method;
    if (targetClass != null) {
      try {
        m = targetClass.getMethod(m.getName(), m.getParameterTypes());
        return this.isFrameAnnotation(m);
      } catch (NoSuchMethodException ignored) {
        //default return value is false.  If we can't find the method, then obviously
        //there is no annotation, so just use the default return value.
      }
    }
    return super.matches(method, targetClass);
  }

  private boolean isFrameAnnotation(Method method) {
    return null != AnnotationUtils.findAnnotation(method, Permissions.class);
  }
}

六、配置shiro

替换AuthorizationAttributeSourceAdvisorShiroAdvisor


  /**
   * 启用注解拦截方式
   * @return AuthorizationAttributeSourceAdvisor
   */
  @Bean
  public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
    AuthorizationAttributeSourceAdvisor advisor = new ShiroAdvisor();
    advisor.setSecurityManager(securityManager());
    return advisor;
  }
首先,我们需要定义一个自定义注解 `@RequiresPermissions`,用于标识需要授权访问的方法,例如: ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface RequiresPermissions { String[] value(); // 权限值 } ``` 然后,我们需要实现一个切面,用于拦截被 `@RequiresPermissions` 标识的方法,并进行权限校验,例如: ```java @Component @Aspect public class PermissionCheckAspect { @Autowired private AuthService authService; @Around("@annotation(requiresPermissions)") public Object checkPermission(ProceedingJoinPoint joinPoint, RequiresPermissions requiresPermissions) throws Throwable { // 获取当前用户 User user = authService.getCurrentUser(); if (user == null) { throw new UnauthorizedException("用户未登录"); } // 获取当前用户的权限列表 List<String> permissions = authService.getUserPermissions(user); // 校验权限 for (String permission : requiresPermissions.value()) { if (!permissions.contains(permission)) { throw new ForbiddenException("没有访问权限:" + permission); } } // 执行目标方法 return joinPoint.proceed(); } } ``` 在切面中,我们首先通过 `AuthService` 获取当前用户及其权限列表,然后校验当前用户是否拥有被 `@RequiresPermissions` 标识的方法所需的所有权限,如果没有则抛出 `ForbiddenException` 异常,如果有则继续执行目标方法。 最后,我们需要在 Spring 配置文件中启用 AOP 自动代理,并扫描切面所在的包,例如: ```xml <aop:aspectj-autoproxy /> <context:component-scan base-package="com.example.aspect" /> ``` 这样,我们就通过 Spring AOP 和自定义注解模拟实现了类似 Shiro 权限校验的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值