Grails check role access for specific controller action

前提是你 提交于 2019-12-04 11:37:13

Use

<sec:ifAllGranted roles="ROLE_ADMIN,ROLE_SUPERVISOR">
  secure stuff here
</sec:ifAllGranted>

or

<sec:ifAnyGranted roles="ROLE_ADMIN,ROLE_SUPERVISOR">
    secure stuff here
</sec:ifAnyGranted>

according the Spring Security Core Grails plugin documentation.

Or simply use the Spring security core taglib with your tag library.

class RoleTagLib {
  static namespace = "role"

  SpringSecurityService springSecurityService

  def link = { attrs, body ->
    User user = (User) springSecurityService.currentUser          
    sec.ifAnyGranted(roles: 'ROLE_ADMIN,ROLE_SUPERVISOR'){
      out << g.link(attrs, body)
    }
  }
}

Ok I found a solution. The method "hasAccess" in SecurityTagLib is based on grails.plugins.springsecurity.securityConfigType in Config.groovy. My initial value was SecurityConfigType.InterceptUrlMap and then I would have defined every url accessible and specify which role can access each of them manually in the grails.plugins.springsecurity.interceptUrlMap

The solution is to change this to SecurityConfigType.Annotation and modify interceptUrlMap to staticRules. Then the method "hasAccess" is based on the annotations defined in the controller and can hide properly the content with my tagLib wrapped from SecurityTagLib.

There is the code in Config.groovy

    grails.plugins.springsecurity.securityConfigType = SecurityConfigType.Annotation
    grails.plugins.springsecurity.staticRules = [
      ... your rules ... for example:
      '/**': ['ROLE_ADMIN_ACCESS'] 
    ]

The code of my tagLib

    class RoleTagLib extends SecurityTagLib {

        static namespace = "role"

        def link = { attrs, body ->
            if (hasAccess(attrs.clone(), "link")) {
                out << g.link(attrs, body)
            }
        }
    }

And I use this to show or hide any link in my .gsp files based on the @Secured annotation put for every action of every controller

    <role:link controller="myController" action="myAction">
      Action
    </role:link>

This is for Grails 2.3

To check action access from another controller or service, do this:

@Secured(["ONE_OF_MY_ROLES"])
class SomeController {

    SecurityTagLib securityTagLib = (SecurityTagLib)Holders.grailsApplication.mainContext.getBean('grails.plugins.springsecurity.SecurityTagLib')

    def show() {
        def access = securityTagLib.hasAccess([controller: 'product', action: 'show'], 'access')
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!