Andrius
Andrius

Reputation: 21118

Java - Spring AOP - stop method from execution using before advice?

How can I use before advice as security measure in Spring AOP.

For example I have this before advice(with pseudo code):

@Before("trigger()")
public void beforeMethod(JoinPoint point){
    Method[] a = point.getSignature().getClass().getDeclaredMethods();
    for(int i=0; i < a.length; i++){
            //if method has such arguments then
        if(a[i] 'has args String name, String role, Int Money'){ 
               //And if these arguments meets such requirements
                if(a[i].argument(Int.class) > 1000 or a[i].argument(String role).equals("normal"))
                    //Stop executing this method
                    a[i].stop
                }
    }
}   

I know this is just pseudo code, so it may not look correct, but I hope you get an idea. Is there some JoinPoint method to stop scanned method if it meets or does not meets some requirements?

Upvotes: 1

Views: 5136

Answers (2)

Nitin Gupta
Nitin Gupta

Reputation: 27

Actually you cannot. http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html

@Before("trigger()")
public void beforeMethod(JoinPoint point){
    Method[] a = point.getSignature().getClass().getDeclaredMethods();
    for(int i=0; i < a.length; i++){
            //if method has such arguments then
        if(a[i] 'has args String name, String role, Int Money'){ 
               //And if these arguments meets such requirements
                if(a[i].argument(Int.class) > 1000 or a[i].argument(String role).equals("normal"))
                     throw new Exception("Operation Not allowed");
                }
    }
} 

Upvotes: 0

micha
micha

Reputation: 49552

How about just throwing an Exception?

if (!isAllowed) {
  throw new NotAuthorizedException(..)
}

Upvotes: 5

Related Questions