Grails 2.4.4 Testing for permission where spring security code is being used

*爱你&永不变心* 提交于 2019-12-07 12:12:27

问题


I am using spock for may application testing and using Grails 2.4.4. I have done domain, controller, and service unit testing. But in controller sections I am stuck with the role wise access. For authentication I am using Spring Security Core Plugin. Below is my 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 do I test that only the user with ROLE_A and ROLE_B can create and save and other cannot? Also I do I check the user is IS_AUTHENTICATED_FULLY to access index action ?


回答1:


From your question, it sounds like you are trying to test whether the Spring Security code is working. My take on unit testing controllers is that 'if I didn't write I'm not testing it.' Services used by my controllers are mocked, configuration values used by my controller are mocked. Likewise, Spring Security behaviors are mocked (in effect). This means accepting some amount of risk related to the plugins that you use in your application. Do you trust Spring Security to handle roles and authorities correctly? I generally do.

I'm more interested in the behaviors of my code, so I generally just bypass the spring check in my Unit tests. If you want to verify the behaviors of your application if the user is or is not logged in, or does or does not have a certain role, you can do that.

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
}


来源:https://stackoverflow.com/questions/31773734/grails-2-4-4-testing-for-permission-where-spring-security-code-is-being-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!