简体   繁体   中英

@PreAuthorize not working when a secured method is called from another secured method in same class

@PreAuthorize    
public void methodA() {
methodB();
}

@PreAuthorize    
public void methodB() { 
}

Here methodA() is interface method and methodB() is called by methodA().

Spring method level security uses Spring AOP that is proxy-based. This means that method calls on an object reference will be calls on the proxy, and as such the proxy will be able to delegate to all of the interceptors (eg @PreAuthorize ) that are relevant to that particular method call.

However, once the call has finally reached the target object, any method calls that it may make on itself are going to be invoked against the this reference, and not the proxy. It means that self-invocation is not going to result in the advice associated with a method invocation getting a chance to execute.

You can find more details here .

Basically, It can work but this is not recommended. Ideally, you should change your design logic. This is your code when JVM runs it.

@PreAuthorize    
public void methodA() {
this.methodB();
}

 @PreAuthorize    
public void methodB() { 
 }

First why it is not working:

Spring method level security is using Spring AOP based proxies, which means whenever you are calling a method, It is being called on a Proxy object(Not on Actual Object) and this object holds the Spring context and enables you to preauthorize.

But when the control is reached to the method called from the proxy, any method called inside that is called on actual object(this) which doesn't hold Spring context. Hence It is not performing any preauthorization on method.

Basically your code is calling methodB() as this.methodB() which is on actual object. If you somehow can get the same proxy (via reflection API or Application context), you can perform the operation desired via below code(not an actual implementation just an idea).

@PreAuthorize    
public void methodA() {
proxyObject.methodB();
}

 @PreAuthorize    
public void methodB() { 
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM