Как использовать пользовательские роли / полномочия в Spring Security? - PullRequest
31 голосов
/ 12 июня 2009

При переносе устаревшего приложения в 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$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» и использую только эту роль в конфигурации, все работает.

Не работает:

 <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> 

Работает:

<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> 

Можно ли использовать собственные имена ролей?

Ответы [ 5 ]

40 голосов
/ 12 июня 2009

Вы используете конфигурацию по умолчанию, которая предполагает, что роли начинаются с префикса "ROLE_". Вам нужно будет добавить пользовательскую конфигурацию безопасности и установить rolePrefix в "";

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

11 голосов
/ 01 декабря 2011

Вот полная конфигурация с использованием выражений доступа (ссылка, предоставляемая @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>
7 голосов
/ 12 марта 2013

Вы также можете всегда использовать выражение (по конфигурации use-expressions="true"), чтобы игнорировать префикс ROLE_.

После прочтения исходного кода Spring Security 3.1 я обнаружил, что use-expressions="true":

Для <security:http >:
HttpConfigurationBuilder#createFilterSecurityInterceptor() будет регистрироваться WebExpressionVoter, но не RoleVoterAuthenticatedVoter;

Для <security:global-method-security >: GlobalMethodSecurityBeanDefinitionParser#registerAccessManager() будет регистрироваться PreInvocationAuthorizationAdviceVoter (условно), затем всегда регистрироваться RoleVoterAuthenticatedVoter, регистрироваться Jsr250Voter условно;

PreInvocationAuthorizationAdviceVoter будет обрабатывать PreInvocationAttribute (PreInvocationExpressionAttribute будет использоваться как реализация), который генерируется в соответствии с @PreAuthorize. PreInvocationExpressionAttribute#getAttribute() всегда возвращать ноль, поэтому RoleVoterAuthenticatedVoter не голосуйте за него.

2 голосов
/ 24 апреля 2014

Используя Spring Security 3.2 , это сработало для меня.

Изменить префикс роли:

<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>

В зависимости от того, где вы хотите применить префикс роли, его можно применять на уровне схемы безопасности или на уровне компонента.

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

Применить префикс роли на уровне обслуживания:

<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>
1 голос
/ 24 августа 2012

Это также может помочь:

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

В основном это говорит о том, что вы должны написать в grails-app / conf / spring / resources.groovy:

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

Это сработало для меня.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...