【问题标题】:SecurityContextHolder.getContext().getAuthentication() is returning Null across requestsSecurityContextHolder.getContext().getAuthentication() 跨请求返回 Null
【发布时间】:2015-08-17 15:52:55
【问题描述】:
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

索引.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() 这里是 Null。

【问题讨论】:

    标签: spring authentication spring-security


    【解决方案1】:

    如果您提供成功身份验证后如何处理 google 重定向到您的网站会更好。

    在 google 重定向 URL 中尝试将 Authentication Object 添加到 SecurityContextHolder,

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

    我尝试了上面的代码,它对我来说工作正常。

    【讨论】:

    • 请在下方找到 Google 身份验证代码
    • 请也向着陆页提供代码。-根据我的理解,在成功进行 google 身份验证后,您没有将身份验证对象设置为 SecurityContextHolder。
    猜你喜欢
    • 2014-04-07
    • 2013-07-08
    • 2019-04-28
    • 2019-06-29
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多