【问题标题】:In Grails, how do I test @Secured annotations in automated tests?在 Grails 中,如何在自动化测试中测试 @Secured 注解?
【发布时间】:2013-05-26 19:10:50
【问题描述】:

我有一个控制器方法,我正在这样注释:

@Secured(['ROLE_ADMIN'])
def save() {
    ... // code ommitted
}

我正在尝试编写一个单元测试来验证只有管理员用户才能访问该 URL:

def "Only the admin user should be able to invoke save"() {
    given:
    def user = createNonAdminUser() // let's pretend this method exists
    controller.springSecurityService = Mock(SpringSecurityService)
    controller.springSecurityService.currentUser >> user

    when:
    controller.save()

    then:
    view ==~ 'accessdenied'
}

但是,返回的视图是save 视图,而不是拒绝访问视图。看起来它完全绕过了 @Secured 注释。有没有办法从单元测试或集成测试中测试@Secured 注释?

【问题讨论】:

  • 你找到解决办法了吗?

标签: unit-testing grails spring-security integration-testing


【解决方案1】:

如果您还没有在createNonAdminUser() 中调用控制器保存,则需要先登录用户。

SpringSecurityUtils.reauthenticate username, password

可能与this问题有关。

【讨论】:

    【解决方案2】:

    试试这个:

    SpringSecurityUtils.doWithAuth('superuser') {
        controller.save()
    }
    

    http://greybeardedgeek.net/2011/05/13/testing-grails-controllers-with-spock/

    【讨论】:

      猜你喜欢
      • 2016-07-18
      • 2021-07-08
      • 2018-02-24
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      相关资源
      最近更新 更多