Grails 2.4.4 Testing permission using spring guard code

I am using spock for testing applications and using Grails 2.4.4. I have passed the domain, controller and service module testing. But in the controller sections, I'm stuck with the role wise access. I am using Spring Core Security Plugin for authentication. Below is a sample code.

@Secured(["IS_AUTHENTICATED_FULLY"])
def index(Integer max) {

}

@Secured(["ROLE_A","ROLE_B"])
def create() {
    respond new DomainName(params)
}

@Transactional
@Secured(["ROLE_A","ROLE_B"])
def save(DomainName DomainNameInstance) {
}

      

How can I check that only the user with ROLE_A and ROLE_B can create and save and others cannot? Also I check that the user IS_AUTHENTICATED_FULLY to access the index action?

+3


source to share


1 answer


From your question, it looks like you are trying to check if the Spring defensive code is working. My control over modular controllers is that "if I hadn't written, I hadn't tested it." The services used by my controllers are mocked, the config values ​​used by my controller are mocked. Likewise, Spring Security Behavior is mocked (in fact). This means accepting some risk associated with the plugins you use in your application. Do you trust Spring Security to properly manage roles and permissions? I generally do.

I'm more interested in the behavior of my code, so I usually just bypassed Spring validation in my unit tests. If you want to test the behavior of your application, if the user is registered or not registered, or has or does not have a specific role, you can do so.



def "test create method without required role"() {
    setup:
    // tell Spring to behave as if the user does not have the desired role(s)
    SpringSecurityUtils.metaClass.static.ifAllGranted = { String role ->
        return false
    }

    when:
    controller.index()

    then:
    // without the required role, what does the controller return?
    controller.response.status == ??

    cleanup:
    SpringSecurityUtils.metaClass = null
}

def "test create method with required role"() {
    setup:
    // tell Spring to behave as if the user has the required role(s)
    SpringSecurityUtils.metaClass.static.ifAllGranted = { String role ->
        return true
    }

    when:
    controller.index()

    then:
    // with the required role(s), what does the controller return?
    controller.response.status == 200
    controller.response.mimeType.name == "application/json"
    controller.response.getText() == "whatever"

    cleanup:
    SpringSecurityUtils.metaClass = null
}

      

0


source







All Articles