How to implement annotation based security using S

2019-06-24 07:32发布

问题:

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.