SecurityContextHolder.getContext()。getAuthentication()在请求之间返回Null

时间:2015-06-03 12:26:51

标签: spring authentication spring-security

SecurityContextHolder.getContext().getAuthentication()
is returning Null

I enter an URL into the browser **http::/myntrac.com/udp**, it calls    
index.jsp and forward the page to Spring Controller

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
 <head>
 <script type="text/javascript" >

 </script>
 </head>
<body>
<jsp:forward page="/udp/auth" />
</body>
</html>


Spring Controller 
--------------------------
It is redirecting to the page on the basis whether user has  
authenticated or not


 @RequestMapping(value = "/auth")
public String authentication()
        throws IOException {
    Authentication auth =  
    SecurityContextHolder.getContext().getAuthentication();
    if(auth == null || !auth.isAuthenticated()) {
        return "redirect:/udp/redirectLogin";
    } else {
        return "redirect:/udp/home";
    }

}

如果用户未经过身份验证,则会重定向到登录页面。身份验证(google api身份验证)后,它会到达登录页面。在这里我检查了SecurityContextHolder.getContext()。getAuthentication()不是Null。

我再次输入网址 http :: / myntrac.com/udp 。由于用户已经过身份验证,因此应该将其重定向到主页而不是登录页面,但它再次进入登录页面但用户会话已经存在。因为SecurityContextHolder.getContext()。getAuthentication()在这里是空的。

1 个答案:

答案 0 :(得分:0)

如果您在成功进行身份验证后提供如何处理Google重定向到您的网站,那会更好。

在Google重定向网址中,尝试将身份验证对象添加到SecurityContextHolder,

    Authentication authentication = new UsernamePasswordAuthenticationToken(u1,null,authorityList);/* null password I am setting 
     u1- username
     authorityList - List<GrantedAuthority>

   */

            SecurityContextHolder.getContext().setAuthentication(authentication);

我尝试了上面的代码,它对我来说很好。