【发布时间】:2017-09-15 08:28:37
【问题描述】:
我正在从事 spring mvc 和 spring 安全项目。在我们的项目中,角色和权限将存储在 db 中,并且那里有不同的角色。我写了下面的代码来限制访问,但是所有的 URL 都对他们有用,请帮助我根据他们的授予权限来限制用户。
安全性.xml
<http use-expressions="true" >
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login login-page="/login.jsp"
login-processing-url="/login"
username-parameter="userName"
password-parameter="password"
authentication-success-handler-ref="authenticationSuccessHandler"
authentication-failure-handler-ref="authenticationFailedHandler"
/>
<logout logout-url="/logout" invalidate-session="true" logout-success-url="/login.jsp?logout=true"/>
<access-denied-handler error-page="/accessDenied"/>
</http>
自定义身份验证提供程序
List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
if(userName.equals("admin")){
System.out.println("++++++ admin user +++++");
AUTHORITIES.add(new SimpleGrantedAuthority("/hello"));
AUTHORITIES.add(new SimpleGrantedAuthority("/hello1"));
AUTHORITIES.add(new SimpleGrantedAuthority("/hello2"));
}else{
AUTHORITIES.add(new SimpleGrantedAuthority("/hello"));
AUTHORITIES.add(new SimpleGrantedAuthority("/hello1"));
}
return new UsernamePasswordAuthenticationToken(userName,null,AUTHORITIES);
在上面的示例中,现在所有用户都可以访问所有 url,但请帮助限制他们只能访问授予他的 url。
【问题讨论】:
-
请阅读spring securitydocs.spring.io/spring-security/site/docs/4.0.3.RELEASE/…的文档。
-
SimpleGrantedAuthority应该扮演一个角色而不是一个 URL。尝试解决这个问题。我也建议你看看这里:baeldung.com/security-spring
标签: spring-mvc spring-security