我正在使用spring security,我似乎无法查看用户是否已成功登录以挽救我的生命,然后获取实际的用户名。 “spring”(SecurityContextHolder)和“J2EE”(request.getUserPrincipal())方式都返回 null。
我的 web.xml
<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>com.company.security.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
....
<servlet>
<servlet-name>agent-desktop</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>agent-desktop</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Spring 配置:
<mvc:resources mapping="/r/**" location="/resources/" />
Spring 安全配置:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<http auto-config="true">
<intercept-url pattern="/agent/**" access="ROLE_USER" />
<intercept-url pattern="/supervisor/**" access="ROLE_USER" />
<form-login login-page="/r/views/login.html" default-target-url="/dashboard" authentication-failure-url="/r/views/loginfailed.html" />
<logout logout-success-url="/logout" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="pw123" authorities="ROLE_USER, ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
这是我的过滤器代码:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(auth != null)
{
String name = auth.getName(); //get logged in username
System.out.println("name:"+name);
User user = (User)auth.getPrincipal();
if(user != null)
System.out.println("user:"+user.getUsername());
}
if(req.getUserPrincipal() != null) // someone has logged in - IT IS ALWAYS NULL
{
/// IT NEVER GETS IN HERE!!!!!!!!!!
最佳答案
我怀疑您错过了在 web.xml 中包含过滤器的情况。您可能想从 here 阅读有关如何配置 spring security 的信息。
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
关于java - 为什么spring security无法获取用户名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23415680/