【问题标题】:Grails 2.4.4 Testing for permission where spring security code is being usedGrails 2.4.4 测试使用弹簧安全代码的权限
【发布时间】:2015-08-02 15:58:53
【问题描述】:

我正在使用 spock 进行应用程序测试并使用 Grails 2.4.4。我已经完成了域、控制器和服务单元测试。但是在控制器部分,我被角色明智的访问所困。对于身份验证,我使用 Spring Security Core Plugin。下面是我的示例代码。

@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) {
}

如何测试只有具有 ROLE_A 和 ROLE_B 的用户可以创建和保存,其他用户不能?我还要检查用户是否是 IS_AUTHENTICATED_FULLY 才能访问索引操作?

【问题讨论】:

    标签: unit-testing testing grails-2.0 spock


    【解决方案1】:

    从您的问题来看,听起来您正在尝试测试 Spring Security 代码是否正常工作。我对单元测试控制器的看法是“如果我不写,我就不会测试它。”我的控制器使用的服务是模拟的,我的控制器使用的配置值是模拟的。同样,Spring Security 行为被模拟(实际上)。这意味着接受与您在应用程序中使用的插件相关的一些风险。您是否相信 Spring Security 能够正确处理角色和权限?我一般都会。

    我对代码的行为更感兴趣,所以我通常只是绕过单元测试中的弹簧检查。如果您想验证您的应用程序的行为,即用户是否已登录,或者是否具有特定角色,您可以这样做。

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-09
      • 2012-08-21
      • 2012-01-07
      • 2019-02-03
      • 2017-07-21
      • 2013-07-16
      • 1970-01-01
      • 2012-09-29
      相关资源
      最近更新 更多