How can I use Spring Security without sessions? How can I use Spring Security without sessions? spring spring

How can I use Spring Security without sessions?


In Spring Security 3 with Java Config, you can use HttpSecurity.sessionManagement():

@Overrideprotected void configure(final HttpSecurity http) throws Exception {    http        .sessionManagement()            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);}


It seems to be even easier in Spring Securitiy 3.0. If you're using namespace configuration, you can simply do as follows:

<http create-session="never">  <!-- config --></http>

Or you could configure the SecurityContextRepository as null, and nothing would ever get saved that way as well.


We worked on the same issue (injecting a custom SecurityContextRepository to SecurityContextPersistenceFilter) for 4-5 hours today. Finally, we figured it out.First of all, in the section 8.3 of Spring Security ref. doc, there is a SecurityContextPersistenceFilter bean definition

<bean id="securityContextPersistenceFilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter">    <property name='securityContextRepository'>        <bean class='org.springframework.security.web.context.HttpSessionSecurityContextRepository'>            <property name='allowSessionCreation' value='false' />        </bean>    </property></bean>

And after this definition, there is this explanation:"Alternatively you could provide a null implementation of the SecurityContextRepository interface, which will prevent the security context from being stored, even if a session has already been created during the request."

We needed to inject our custom SecurityContextRepository into the SecurityContextPersistenceFilter. So we simply changed the bean definition above with our custom impl and put it into the security context.

When we run the application, we traced the logs and saw that SecurityContextPersistenceFilter was not using our custom impl, it was using the HttpSessionSecurityContextRepository.

After a few other things we tried, we figured out that we had to give our custom SecurityContextRepository impl with the "security-context-repository-ref" attribute of "http" namespace. If you use "http" namespace and want to inject your own SecurityContextRepository impl, try "security-context-repository-ref" attribute.

When "http" namespace is used, a seperate SecurityContextPersistenceFilter definition is ignored. As I copied above, the reference doc. does not state that.

Please correct me if I misunderstood the things.