简体   繁体   中英

Accessing a controller method's required roles/authorities from a filter

Is it possible to retrieve a list of the roles/authorities required for a particular controller action/method in a Grails Filter?

Assuming the Spring Security Core (2.0.x) plugin installed and a Controller using @Secured annotations such as:

class PersonController {

    @Secured(['ROLE_MANAGER','ROLE_USER'])
    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond Person.list(params), model:[personInstanceCount: Person.count()]
    }

    @Secured(['ROLE_MANAGER'])
    def show(Person personInstance) {
        respond personInstance
    }
}

If a user navigated to the index action, the filter would get ['ROLE_MANAGER', 'ROLE_USER'] and if they navigated to show, the filter would get ['ROLE_MANAGER']. I tried injecting the objectDefinitionSource into the filter and using objectDefinitionSource.allConfigAttributes like the following:

class MyFilters {

    def objectDefinitionSource    

    def filters = {
        all(controller:'assets', action:'*', invert: true) {
            before = {
                // get list of spring security roles required for the controller's action
                objectDefinitionSource.allConfigAttributes.each { println it }
                // additional filter behavior...
            }
        }
    }
 }

but as the method suggests, it displays all the roles defined in the app not just those specific to that action.

Try this code

def ctrlClass = grailsApplication.getArtefactByLogicalPropertyName("Controller", controllerName).clazz
def roles = ctrlClass.getDeclaredMethod(actionName).getAnnotation(grails.plugin.springsecurity.annotation.Secured).value()

It should return ['ROLE_MANAGER','ROLE_USER'] for your "index" action and ['ROLE_MANAGER'] for your "show" action

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM