从过滤器访问控制器方法所需的 roles/authorities

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

是否可以在 Grails 过滤器中检索特定控制器 action/method 所需的 roles/authorities 列表?

假设安装了 Spring 安全核心 (2.0.x) 插件和使用 @Secured 注释的控制器,例如:

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
    }
}

如果用户导航到索引操作,过滤器将获得 ['ROLE_MANAGER'、'ROLE_USER'],如果用户导航到显示,过滤器将获得 ['ROLE_MANAGER']。我尝试将 objectDefinitionSource 注入过滤器并使用 objectDefinitionSource.allConfigAttributes 如下所示:

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...
            }
        }
    }
 }

但正如该方法所建议的那样,它会显示应用中定义的所有角色,而不仅仅是那些特定于该操作的角色。

试试这个代码

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

您的 "index" 操作应该 return ['ROLE_MANAGER','ROLE_USER'] 并且您的 "show" 操作应该 ['ROLE_MANAGER']