Java 春天:SecurityContextHolder.getContext().getAuthentication().getPrincipal() 返回 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23358803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:11:25  来源:igfitidea点击:

Spring: SecurityContextHolder.getContext().getAuthentication().getPrincipal() returns null

javaspringprincipalcontext

提问by Poppy

In My MVC application, even after login when I am trying to get the principal object using,

在我的 MVC 应用程序中,即使在我尝试使用主体对象登录后,

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

the authentication is returned as null.

身份验证返回为空。

In Spring-security context,

在 Spring 安全上下文中,

<intercept-url pattern="/test/user/login" access="IS_AUTHENTICATED_ANONYMOUSLY" />

Servlet mapping in Web.xml:

Web.xml 中的 Servlet 映射:

<servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

I am new to MVC implementation. Please help me in fixing this.

我是 MVC 实现的新手。请帮我解决这个问题。

回答by user2292916

It looks like Spring Security instantiate a new context every time there is a "redirect".
So getContext()returns a new objectrather the one you used in login. Someone suggested to get the context from session.
See the answer to this post.
"Spring's SecurityContextHolder.getContext().getAuthentication() returns null after RedirectView is used in HTTPS/SSL"

每次出现“重定向”时,Spring Security 似乎都会实例化一个新的上下文。
因此getContext()返回一个新对象,而不是您在登录时使用的对象。有人建议从 session 获取上下文
看到这个帖子的答案。
在 HTTPS/SSL 中使用 RedirectView 后,Spring 的 SecurityContextHolder.getContext().getAuthentication() 返回 null