javaspring-securitylegacy-app

What's the best way to support the "ROLE_" prefix for Spring Security?


If you are supporting an older application that does not have prefixes on all the roles, what is the best way to support the "ROLE_" prefix? Is there a way to ignore or omit it from loading?


Solution

  • There doesn't seem to be an easy way to ignore the prefix within the normal spring security configuration. However, I found that you can easily append "ROLE_" to all your roles when loading from the database. I just use the CONCAT function within MySQL to add "ROLE_" to all roles. See below:

    <authentication-manager>
        <authentication-provider>
            <password-encoder hash="md5"/>
            <jdbc-user-service
                data-source-ref="dataSource"
                authorities-by-username-query="SELECT username, CONCAT('ROLE_', rolename) as authority FROM user_role WHERE active = 1 AND username = ?"
                users-by-username-query="SELECT username, password, active FROM user WHERE username = ?" />
        </authentication-provider>
    </authentication-manager>
    

    This concept can also be applied if you create your own class using the UserDetailsService interface:

    <!-- Select users and user_roles from database -->
    <authentication-manager alias="authenticationManager">
        <authentication-provider user-service-ref="myUserDetailsService">
            <password-encoder ref="encoder" />
        </authentication-provider>
    </authentication-manager>
    
    <beans:bean id="encoder" class="com.my.security.MyPasswordEncoder" />
    

    NOTE: I use an "alias" for the "authentication-manager" instead of an ID, because my customization seems to be ignored during the authentication process if I override the default ID.