Spring Security - Prevent AccessDeniedException from stopping application normal flow
I'm using Spring Secuirty 3 with ACL module. I'm securing the methods with @PreAuthentication annotations using a custom PermissionEvaluator. Its working fine, however every time the PermissionEvaluator returns an ACCESS_DENIED an AccessDeniedException is thrown at some point and this stops the application execution. The desired behaivore will be that when the PermissionEvaluator returns and ACCESS_DENIED, the secured method call is only prevented (skipped) and the rest of the application kee开发者_JAVA百科ps running normally. Does anyone have an idea on how to achieve this?
If you wrap each call where you want this to happen in a try...catch
, you can get this behavior. Basically, since it's an exception, any normal exception handling will apply to it. If your application can handle that exception and continue normally, then do exactly that!
Here's an example of what I mean:
// The 1st method that could be denied but you want to continue execution after
try {
// Call method A that will throw the exception
} catch (/*The exception you expect to be thrown and want to continue after*/){}
// The 2nd method that could be denied but you want to continue execution after
try {
// Call method B that will throw the exception
} catch (/*The exception you expect to be thrown and want to continue after*/){}
etc.
Yes, it does add a lot of overhead to calling those methods, but it is a fairly simple way of allowing execution to continue after an exception is raised.
I would also argue that it is also more correct, since the calling code does know how to deal with those exceptions. This also doesn't require any additional Spring configuration, which means that the code behavior remains closer to the default and does not rely on external configurations to determine it's behavior.
精彩评论