4

I have a controller method that I'm annotating like so:

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

I'm trying to write a unit test to verify that only the admin user can hit the 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'
}

However, the view returned is the save view and not the access denied view. It looks like it's bypassing the @Secured annotation altogether. Is there a way to test @Secured annotations from either a unit test or integration test?

Daniel T.
  • 37,212
  • 36
  • 139
  • 206

2 Answers2

2

Try this:

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

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

zoran119
  • 10,657
  • 12
  • 46
  • 88
0

You would need to login the user before calling controller save if you are not doing it already in createNonAdminUser().

SpringSecurityUtils.reauthenticate username, password

Possibly related to this question.

Community
  • 1
  • 1
dmahapatro
  • 49,365
  • 7
  • 88
  • 117