I would like to create a class that adds custom methods for use in spring security expression language for method-based authorization via annotations.
For example, I would like to create a custom method like 'customMethodReturningBoolean' to be used somehow like this:
@PreAuthorize("customMethodReturningBoolean()")
public void myMethodToSecure() {
// whatever
}
My question is this. If it is possible, what class should I subclass to create my custom methods, how would I go about configuring it in the spring xml configuration files and come someone give me an example of a custom method used in this way?
Thanks ericacm, but it does not work for a few reasons:
The differences are that we call the existing createEvaluationContext method and then add our custom root object. Finally I just returned an StandardEvaluationContext object type since MethodSecurityEvaluationContext would not resolve in the compiler (they are both from the same interface). This is the code that I now have in production.
Make MethodSecurityExpressionHandler use our custom root:
This replaces the default root by extending SecurityExpressionRoot. Here I've renamed hasRole to hasEntitlement:
Finally update securityContext.xml (and make sure it's referenced from your applcationContext.xml):
Note: the @Secured annotation will not accept this override as it runs through a different validation handler. So, in the above xml I disabled them to prevent later confusion.
You'll need to subclass two classes.
First, set a new method expression handler
myMethodSecurityExpressionHandler
will be a subclass ofDefaultMethodSecurityExpressionHandler
which overridescreateEvaluationContext()
, setting a subclass ofMethodSecurityExpressionRoot
on theMethodSecurityEvaluationContext
.For example:
None of the mentioned techniques will work anymore. It seems as though Spring has gone through great lengths to prevent users from overriding the SecurityExpressionRoot.
EDIT 11/19/14 Setup Spring to use security annotations:
Create a bean like this:
Then do something like this in your jsp:
Or annotate a method:
Additionally, you may use Spring Expression Language in your
@PreAuthorize
annotations to access the current authentication as well as method arguments.For example:
Then update your
@PreAuthorize
to match the new method signature: