Search This Blog

Wednesday, 8 June 2011

Custom Roles in Spring Security

By default, Spring Security accepts roles like 'ROLE_ADMIN', 'ROLE_USER'.
We can change this default behavior by changing the Role Prefix from "Role_" to "".
In order to achieve this, we will add following code in the applicationContext-security.xml of our Login Example.
    <beans:bean id="roleVoter"
        class="org.springframework.security.vote.RoleVoter ">
        <beans:property name="rolePrefix" value="" />
    </beans:bean>
    <beans:bean id="authenticatedVoter"  class="org.springframework.security.vote.AuthenticatedVoter" />
    <beans:bean id="accessDecisionManager"  class="org.springframework.security.vote.AffirmativeBased">
    <beans:property name="decisionVoters">
        <beans:list>
            <beans:ref bean="roleVoter" />
            <beans:ref bean="authenticatedVoter" />
        </beans:list>
    </beans:property>
    </beans:bean>
After this, we can use our custom roles like 'admin' and 'user' instead of 'ROLE_ADMIN' and 'ROLE_USER'.
<authentication-provider>
        <password-encoder hash="md5"/>
        <user-service>
            <user name="sandeep" password="00f1de4e151ccfc1fc9ff735a5efc479" authorities="admin,user" />
            <user name="vijay" password="e555f863fb09593119fe2f3459e9783a" authorities="user" />
        </user-service>
 </authentication-provider> 

No comments:

Post a Comment