I have a Spring MVC application.It uses its own custom Login page. Upon successful login, a ‘LOGGED_IN_USER’ object is placed in the HTTPSession.
I want to allow only authenticated users to access URLs. I know i can achieve this by using a web filter. But, This part i want to do using Spring Security (my check will remain the same – look for ‘LOGGED_IN_USER’ object in HTTPSession, if present you are logged in).
My constraint is i cannot change Login behavior at present – that will not use Spring Security yet.
What aspect of Spring Security can i use to achieve this part alone – check if the request is authenticated (from logged in user)?
There are at least 4 different ways:
spring security XML configuration
this is the easiest way
Per @Secured Annotation
requires
<global-method-security secured-annotations="enabled" />Per @PreAuthorize Annotation
requires
<global-method-security pre-post-annotations="enabled" />Programmatic
Custom Expression
If the built-in expressions are not enough, you can extend them. How to extend the SpEL Expressions for the method annotations is discussed for example here:
But for the interceptor
<security:intercept-url ... access="myCustomAuthenticatedExpression" />there is a slightly different approach possible, that does not need to deal with the private class problem. — I have only done it for Spring Security 3.0, but I hope it works for 3.1 too.1.) you need to create a new class that extends from
WebSecurityExpressionRoot(Prefix Web is the important part!).2.) you need a extend the
DefaultWebSecurityExpressionRootHandlerto have a handler that provides your custom expression root3.) Then you need to register your handler with the voters
Spring Security 3.1 Update
Since Spring Security 3.1 it is a bit easier to implement a custom expression. One does not longer need to sublcass
WebSecurityExpressionHandlerand overridecreateEvaluationContext. Instead one sublassAbstractSecurityExpressionHandler<FilterInvocation>or its subclassDefaultWebSecurityExpressionHandlerand overrideSecurityExpressionOperations createSecurityExpressionRoot(final Authentication a, final FilterInvocation f).