SecurityContextHolder.getContext()。getAuthentication()返回null

我想使用以下代码从spring Security手动绕过用户:

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"; 

虚拟登录页面(由磁贴处理)在内部调用同一个控制器中的不同请求映射,我试图获得这样的身份validation。

 SecurityContextHolder.getContext().getAuthentication() 

我在哪里无效!

请帮忙!

所以我发现了实际的问题! 问题是我在security-context.xml中用security =“none”标记了整个控制器。 因此当它从第一个链接反弹到第二个链接时,它会通过任何安全上下文! 抱歉,麻烦的家伙们。

附加答案:如果您想获取非安全URL的登录用户详细信息,那么您可以将它们添加到安全URL并指定为“permitAll”,如下所示:

  //...  //...  

然后,您将能够在登录时检查登录用户或获取凭据。

您的localUser为null。因此,auth变为null。因此,安全上下文中未添加任何身份validation对象。

请查看文档

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

最好有一个customUserDetailsS​​ervice

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

那你可以用

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

尝试这个:

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