Java Spring安全自动身份验证不工作
我在应用程序中使用spring安全性。当用户想要访问/privatePages/*时,将显示一个登录屏幕以进行身份验证。这个很好用。我想让一些东西作为访客访问,所以在我的控制器中,我做了如下操作:Java Spring安全自动身份验证不工作,java,spring-mvc,spring-security,Java,Spring Mvc,Spring Security,我在应用程序中使用spring安全性。当用户想要访问/privatePages/*时,将显示一个登录屏幕以进行身份验证。这个很好用。我想让一些东西作为访客访问,所以在我的控制器中,我做了如下操作: Authentication authentication = new UsernamePasswordAuthenticationToken("SAMPLE", "SAMPLE", getAuthority()); //authentication.setAuthenticated(true); S
Authentication authentication = new UsernamePasswordAuthenticationToken("SAMPLE", "SAMPLE", getAuthority());
//authentication.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(authentication);
public Collection<GrantedAuthority> getAuthority() {
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
GrantedAuthority grantedAuthority = new GrantedAuthority() {
public String getAuthority() {
return "ROLE_RequiredRole";
}
};
grantedAuthorities.add(grantedAuthority);
return grantedAuthorities;
}
但是,我无法访问/privatePages/somePage.jsp
。它仍然会将我重定向到登录页面。我错过什么了吗
更新
<http pattern="/privatePages/**" auto-config="true" use-expressions="true" authentication-manager-ref="myManager" create-session="never">
<session-management invalid-session-url="/privatePages/login" />
<intercept-url pattern="/privatePages" access="hasRole('RequiredRole')"/>
<intercept-url pattern="/privatePages/" access="hasRole('RequiredRole')"/>
<form-login
login-page="/privatePages/login" . . . .
您正在对/privatePages/**
制定规则,这意味着该规则将应用于前缀为localhost:8080/privatePages/…
的所有URL,如果在该规则中,您强制执行某种所需的身份验证,那么无论您在控制器中做了什么,它都会询问您,因为您的请求在到达该阶段之前会通过安全过滤器
在SecurityConfig中,尝试执行以下操作:
<http auto-config="true">
<intercept-url pattern="/privatePages" access="ROLE_RequredRole" />
<intercept-url pattern="/privatePages/somePage.jsp" access="ROLE_ANONYMOUS" />
</http>
这里我们使用的是ROLE\u ANONYMOUS
,这意味着该角色不需要任何身份验证。有关更多信息,请参阅。如果在安全配置中您对/privatePages/*
有权限,例如:http.authorizeRequests().antMatchers(“/privatePages/*”).hasAnyRole(“任意”);
然后它将在前缀/privatePages/…
的所有URL上强制执行该规则。相反,您应该使/privatePages/somePage.jsp
具有匿名()
scope,在设置了需要身份验证的规则之后。我希望它在没有凭据的情况下登录。我按照您的指示做了。它在没有使用ROLE\u ANONYMOUS的情况下工作。我只需删除/privatePages/**
@NoahMartin是的,正如我之前试图说的那样,在路径前面有**
将强制执行路径之后的所有路径至少,也应将其纳入同一规则。
<http auto-config="true">
<intercept-url pattern="/privatePages" access="ROLE_RequredRole" />
<intercept-url pattern="/privatePages/somePage.jsp" access="ROLE_ANONYMOUS" />
</http>