Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SecurityContextHolder.getContext().getAuthentication() returning null

I want to manually bypass the user from spring Security using the following code:

User localeUser = new User();
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(localeUser ,null, localeUser .getAuthorities());
SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(auth);
        // Create a new session and add the security context.
        HttpSession session = request.getSession(true);
        session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
return "dummyLogin";

The dummy login page(handled by tiles)internally calls a different Request Mapping in the same controller where i am trying to get the Authentication something like this.

SecurityContextHolder.getContext().getAuthentication()

Where i am getting null?

like image 954
Rajesh Wadhwa Avatar asked Mar 05 '14 07:03

Rajesh Wadhwa


2 Answers

So, I found the actual problem! The issue was that I had marked the whole controller with security="none" in the security-context.xml. So, when it was bounced from the first link to the 2nd, it didn't pass any security context with it!! Sorry for the trouble, guys.

like image 113
Rajesh Wadhwa Avatar answered Sep 21 '22 14:09

Rajesh Wadhwa


Additional Answer: If you want to get logged-in user details for a non-secured url then you can add them to secured urls and assign as "permitAll" like this:

<http>
    //...

    <intercept-url pattern="/your/url/**" access="permitAll"/>

    //...
</http>

Then, you will be able to check the logged-in user if logged-in or get the credentials.

like image 27
Bahadir Tasdemir Avatar answered Sep 22 '22 14:09

Bahadir Tasdemir