Spring Security: Authentication returns null

authenticationsecurityspringstruts2

I have configured a Spring bean as follows to return a SecurityContext:

<bean id="securityContext" class="org.springframework.security.context.SecurityContextHolder"
    factory-method="getContext">
</bean>  

When I use this bean the Authentication object returns null.

Authentication authentication = securityContext.getAuthentication();
GrantedAuthority[] authorities = authentication.getAuthorities();

The second line above causes an NPE. Which seems odd to me, as the following code returns the authorities as expected:

GrantedAuthority[] authorities =   
SecurityContextHolder.getContext().getAuthentication().getAuthorities();

Basically I'm trying to eliminate the static call to SecurityContextHolder.getContext() to make my code more testable.

Any thoughts on how to remedy this? Why is the SecurityContext returned by Spring not able to return the authorities while a static call from within my own code can?

FYI I am executing the code from within a Struts 2 Action.

Best Solution

SecurityContextHolder.getContext() returns the context associated with the current thread. In bean instantiation the context stored in your bean is different than the context you need when your application is running. I don't think that it is possible to store the context in a bean and use this all the time.