Подтвердить что ты не робот

Как использовать пользовательские роли/полномочия в Spring Security?

При переносе устаревшего приложения на spring безопасность я получил следующее исключение:

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 я вижу только такие роли, как "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> 

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

4b9b3361

Ответ 1

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

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

Ответ 2

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

Ответ 3

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

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

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

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

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

Ответ 4

Используя 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>

В зависимости от того, где вы хотите применить префикс роли, его можно применять на уровне схемы безопасности или 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>