Search code examples
springspring-mvcauthenticationspring-securityspring-annotations

Spring MVC / Security No-Static Role Based Authentication


I implemented spring-mvc based java application via no-xml. How to do set rol based authentication for each controller method?

I don't want to static role name facultyMember like following code:

@PreAuthorize("hasRole('facultyMember')")
public Newsletter getFacultyNews() { }

Solution

  • Although it seems odd that the permission to access a service is to be made dynamic, you can try and use an external properties file:

    In your application context:

    <bean id="myProp" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
             <list>
                  <value>file:///pathToExternalPropertyFile/myProp.properties</value>
               </list>
        </property>
    </bean>
    

    Then in your controller class:

    @Value("#{myProp['dynamicRole']}")
    private String dynamicRole;
    
    @PreAuthorize("hasRole('"+dynamicRole +"')")
    public Newsletter getFacultyNews() { }