Spring: SecurityContextHolder.getContext().getAuthentication().getPrincipal() returns null

Poppy picture Poppy · Apr 29, 2014 · Viewed 14.6k times · Source

In My MVC application, even after login when I am trying to get the principal object using,

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

the authentication is returned as null.

In Spring-security context,

<intercept-url pattern="/test/user/login" access="IS_AUTHENTICATED_ANONYMOUSLY" />

Servlet mapping in Web.xml:

<servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

I am new to MVC implementation. Please help me in fixing this.

Answer

user2292916 picture user2292916 · Jul 22, 2014

It looks like Spring Security instantiate a new context every time there is a "redirect".
So getContext() returns a new object rather the one you used in login. Someone suggested to get the context from session.
See the answer to this post.
"Spring's SecurityContextHolder.getContext().getAuthentication() returns null after RedirectView is used in HTTPS/SSL"