2017-04-19 79 views
0

我正在研究弹簧mvc和弹簧安全项目。在我们的项目中,角色和权限将存储在db中,并且存在不同的角色。我已经编写了下面的代码来限制访问,但所有的URL都适用于所有的URL,请帮助我根据他们的授权机构限制用户。弹簧安全动态角色

的security.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,但请帮助限制他们都只能访问网址授予他。

+1

请阅读spring安全文档http://docs.spring.io/spring-security/site/docs/4.0.3.RELEASE/reference/htmlsingle/#jc-httpsecurity。 – akuma8

+1

'SimpleGrantedAuthority'应该扮演一个角色而不是URL。试着解决这个问题。我也建议你看看这里:http://www.baeldung.com/security-spring – akuma8

回答

0

试试这个,

<http use-expressions="true" > 
    <intercept-url pattern="/**" access="hasRole('ROLE_USER') or hasRole('ROLE_ADMIN') or hasRole('ROLE_MYCUSTOMROLE')"/> 
    <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> 

注1:使用安全名称空间的清晰度和访问属性应该有一定的作用,没有网址

强似URL来的GrantedAuthority通过一些角色,甚至可以做更好的做一个User pojo类并实现UserDetails,这样你就可以避免大量的锅炉代码。