如何在Spring Security中使用自定义角色/权限?

在将旧应用程序迁移到spring安全性时,我遇到以下exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_filterChainProxy': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_filterChainList': Cannot resolve reference to bean '_filterSecurityInterceptor' while setting bean property 'filters' with key [3]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '_filterSecurityInterceptor': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Unsupported configuration attributes: [superadmin] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) 

在旧的应用程序中,有“superadmin”,“editor”,“helpdesk”等角色。但是在所有Spring Security示例中,我只看到像“ROLE_”(“ROLE_ADMIN”等)这样的角色。 当我将“superadmin”重命名为“ROLE_ADMIN”并且仅在配置中使用此角色时,一切正常。

不起作用:

      

作品:

     

可以使用自定义角色名称吗?

您正在使用默认配置,该配置期望角色以"ROLE_"前缀开头。 您必须添加自定义安全配置并将rolePrefix设置为“”;

http://forum.springsource.org/archive/index.php/t-53485.html

这是一个使用访问表达式的完整配置(@rodrigoap提供的链接似乎有点过时):

             

您也可以始终使用表达式(通过config use-expressions="true" )来忽略ROLE_前缀。

在阅读Spring Security 3.1源代码后,我发现use-expressions="true"

对于
HttpConfigurationBuilder#createFilterSecurityInterceptor()将注册WebExpressionVoter但不注册RoleVoterAuthenticatedVoter ;

对于GlobalMethodSecurityBeanDefinitionParser#registerAccessManager() PreInvocationAuthorizationAdviceVoterGlobalMethodSecurityBeanDefinitionParser#registerAccessManager()将注册PreInvocationAuthorizationAdviceVoter (有条件地),然后始终注册RoleVoterAuthenticatedVoter ,有条件地注册Jsr250Voter ;

PreInvocationAuthorizationAdviceVoter将处理PreInvocationAttribute (PreInvocationExpressionAttribute将用作实现),它是根据@PreAuthorize生成的。 PreInvocationExpressionAttribute#getAttribute()始终返回null,因此RoleVoterAuthenticatedVoter不会对其进行投票。

使用Spring Security 3.2 ,这对我有用。

更改角色前缀:

             

根据您要应用角色前缀的位置,可以在安全架构级别或Bean级别应用它。

  

在服务级别应用角色前缀:

      

这也可能有所帮助:

http://forum.springsource.org/showthread.php?96391-Spring-Security-Plug-in-ROLE_-prefix-mandatory

在Bassically,它说你必须用grails-app / conf / spring / resources.groovy写:

 roleVoter(org.springframework.security.access.vote.RoleVoter) { rolePrefix = '' } 

它对我有用。