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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/986892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:54:43  来源:igfitidea点击:

How do I use custom roles/authorities in Spring Security?

javaspringspring-security

提问by D. Wroblewski

While migrating a legacy application to spring security I got the following exception:

在将遗留应用程序迁移到 Spring Security 时,我遇到了以下异常:

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.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.getObject(AbstractBeanFactory.java:264)

In the old application there are roles like "superadmin", "editor", "helpdesk" etc. But in all Spring Security examples I only see roles like "ROLE_" ("ROLE_ADMIN" etc). When I rename "superadmin" to "ROLE_ADMIN" and only use this role in the config, everything works.

在旧应用程序中,有“超级管理员”、“编辑器”、“帮助台”等角色。但在所有 Spring Security 示例中,我只看到“ROLE_”(“ROLE_ADMIN”等)之类的角色。当我将“超级管理员”重命名为“ROLE_ADMIN”并且仅在配置中使用此角色时,一切正常。

Doesn't work:

不起作用:

 <http auto-config="true">                                      
    <intercept-url pattern="/restricted/**" access="superadmin"/>
    <form-login
        authentication-failure-url="/secure/loginAdmin.do?error=true"
        login-page="/secure/loginAdmin.do" />        
</http> 

Works:

作品:

<http auto-config="true">                                      
    <intercept-url pattern="/restricted/**" access="ROLE_ADMIN"/>
    <form-login
        authentication-failure-url="/secure/loginAdmin.do?error=true"
        login-page="/secure/loginAdmin.do" />        
</http> 

Is possible to use custom role names?

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

采纳答案by rodrigoap

You are using the default configuration which expects that roles starts with the "ROLE_"prefix. You will have to add a custom security configuration and set rolePrefixto "";

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

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

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

回答by Tomasz Nurkiewicz

Here is a complete configuration using access expressions (link provided by @rodrigoap seems a little bit outdated):

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

<http
        access-decision-manager-ref="accessDecisionManager"
        use-expressions="true">

<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
    <beans:property name="decisionVoters">
        <beans:list>
            <beans:bean class="org.springframework.security.web.access.expression.WebExpressionVoter"/>
            <beans:bean class="org.springframework.security.access.vote.RoleVoter">
                <beans:property name="rolePrefix" value=""/>
            </beans:bean>
            <beans:bean class="org.springframework.security.access.vote.AuthenticatedVoter"/>
        </beans:list>
    </beans:property>
</beans:bean>

回答by Tomas Romero

This might also help:

这也可能有帮助:

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

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

Bassically, it says you have to write in grails-app/conf/spring/resources.groovy:

基本上,它说您必须在 grails-app/conf/spring/resources.groovy 中编写:

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

It worked for me.

它对我有用。

回答by btpka3

You can also always using expression (by config use-expressions="true") to ignore ROLE_prefix.

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

After reading Spring Security 3.1 source code, I found when use-expressions="true":

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

For <security:http >:
HttpConfigurationBuilder#createFilterSecurityInterceptor()will regist WebExpressionVoterbut not RoleVoterAuthenticatedVoter;

对于<security:http >
HttpConfigurationBuilder#createFilterSecurityInterceptor()会注册WebExpressionVoter但不会RoleVoterAuthenticatedVoter

For <security:global-method-security >: GlobalMethodSecurityBeanDefinitionParser#registerAccessManager()will regist PreInvocationAuthorizationAdviceVoter(conditionally), then always regist RoleVoterAuthenticatedVoter, regist Jsr250Voterconditionally;

For <security:global-method-security >: GlobalMethodSecurityBeanDefinitionParser#registerAccessManager()will regist PreInvocationAuthorizationAdviceVoter(conditionally), then always regist RoleVoter, AuthenticatedVoter, registry Jsr250Voter;

PreInvocationAuthorizationAdviceVoterwill process PreInvocationAttribute(PreInvocationExpressionAttribute will be used as implementation) which is generated according @PreAuthorize. PreInvocationExpressionAttribute#getAttribute()always return null, so RoleVoterAuthenticatedVoterdo not vote it.

PreInvocationAuthorizationAdviceVoter将处理PreInvocationAttribute(PreInvocationExpressionAttribute 将用作实现)根据 生成@PreAuthorizePreInvocationExpressionAttribute#getAttribute()总是返回null,所以RoleVoterAuthenticatedVoter不要投票。

回答by user2601995

Using Spring Security 3.2, this worked for me.

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

Change Role Prefix:

更改角色前缀:

<beans:bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter">
    <beans:property name="rolePrefix" value="NEW_PREFIX_"/>
</beans:bean>

<beans:bean id="authenticatedVoter" class="org.springframework.security.access.vote.AuthenticatedVoter"/>   

<beans:bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
    <beans:constructor-arg >
        <beans:list>
            <beans:ref bean="roleVoter"/>
            <beans:ref bean="authenticatedVoter"/>
        </beans:list>
    </beans:constructor-arg>
</beans:bean>

Depending on where you want to apply the Role Prefix it can be applied at the Security schema level or bean level.

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

<http access-decision-manager-ref="accessDecisionManager" use-expressions="true">

Apply Role Prefix at Service Level:

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

<beans:bean id="myService" class="com.security.test">
    <security:intercept-methods  access-decision-manager-ref="accessDecisionManager">
        <security:protect access="NEW_PREFIX_ADMIN"/>
    </security:intercept-methods>
</beans:bean>