How to implement annotation based security using Spring AOP?

假装没事ソ 提交于 2019-12-10 15:59:20

问题


I'm new to Spring AOP (and AOP in general), need to implement the following:

@HasPermission(operation=SecurityOperation.ACTIVITY_EDIT, object="#act")
public Activity updateActivity(Activity act)
{
   ...
}

@HasPermission is my custom annotation, which will be used to mark all methods requiring pre-authorization. I'm using my custom implementation of security checks based on Apache Shiro. Generally, I guess that I will need to define pointcut which matches all annotated methods and also provide implementation of the aspect (either before or around).

Questions I have are re. aspect implementation.

  • How do I extract operation and object parameters from the annotation?
  • How can I resolve SpEL expression in object definition and get object passed as 'act' parameter?

回答1:


I know it's a late answer but after we were migrating some JavaEE project to Spring we made some basic security model based on AspectJ:

Firstly we annotate our service methods with custom @OperationAuthorization :

@OperationAuthorization
public ListOfUserGroupsTo getUserGroupsByClientId(Integer clientId) throws GenericException {
    return userGroupRepository.getAllUserGroupsForClient(clientId);
}

Then we have a class with @Aspect & @Component annotations which intercepts methods with specific annotations:

@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);
}

In AuthorizationService a method with all arguments are passed. Check whether the client is authorized to get user groups. If it's not: throw our Exception and method stops.



来源:https://stackoverflow.com/questions/17930237/how-to-implement-annotation-based-security-using-spring-aop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!