如何使用 Spring AOP 实现基于注解的安全性?

Ser*_*rov 5 java aop spring aspectj spring-el

我是 Spring AOP(以及一般的 AOP)的新手,需要实现以下内容:

@HasPermission(operation=SecurityOperation.ACTIVITY_EDIT, object="#act")
public Activity updateActivity(Activity act)
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

@HasPermission 是我自定义的注解,用来标记所有需要预授权的方法。我正在使用基于 Apache Shiro 的自定义安全检查实现。一般来说,我想我需要定义切入点来匹配所有带注释的方法,并提供方面的实现(之前或周围)。

我的问题是重新。方面的实施。

  • 如何从注释中提取操作对象参数?
  • 如何解析对象定义中的 SpEL 表达式并将对象作为“act”参数传递?

Iva*_*cki 0

我知道这是一个迟到的答案,但在我们将一些 JavaEE 项目迁移到 Spring 之后,我们基于AspectJ制作了一些基本的安全模型:

首先,我们使用自定义@OperationAuthorization注释我们的服务方法:

@OperationAuthorization
public ListOfUserGroupsTo getUserGroupsByClientId(Integer clientId) throws GenericException {
    return userGroupRepository.getAllUserGroupsForClient(clientId);
}
Run Code Online (Sandbox Code Playgroud)

然后我们有一个带有@Aspect@Component注释的类,它拦截具有特定注释的方法:

@Aspect 
@Component
public class AuthorizationAspect {

@Autowired
AuthorizationService authorizationService;

@Before(value = "@annotation(ch.avelon.alcedo.authorization.annotations.OperationAuthorization)")
public void before(JoinPoint joinPoint) throws Throwable {
    Object[] args = joinPoint.getArgs();
    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();

    authorizationService.checkOperationAuthorization(method, args);
}
Run Code Online (Sandbox Code Playgroud)

AuthorizationService中,传递带有所有参数的方法。检查客户端是否有获取用户组的权限。如果不是:抛出异常并且方法停止。