SecurityContextHolder.getContext().getAuthenticati

2019-04-05 22:01发布

问题:

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!!!.

Please helpp!

回答1:

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 dint pass any security context with it!! Sorry fr the trouble guys.



回答2:

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.



回答3:

Your localUser is null.So the auth become null.So no authentication object has been added to the security context.

Please have look at the doc

http://docs.spring.io/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/core/userdetails/User.html

It is better to have a customUserDetailsService

public class CustomUserDetailsService implements UserDetailsService 

//implement the method which return a UserDetails Object
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException 

then you can use

    UserDetails userDetails= customUserDetailsService.loadUserByUsername("name"); 
Authentication authentication= new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()) ; 
SecurityContextHolder.getContext().setAuthentication(authentication);


回答4:

Try this:

Authentication authentication=SecurityContextHolder.getContext().getAuthentication();
localeUser .setUserNm(authentication.getName());