如何在单元测试中对用户进行Spring Security安全认证

Bar*_*art 10 grails spring-security

我使用带有grails 2.0的spring security core plugin(1.2.7)

假设我有一个使用@Secured注释的方法的控制器.

class ArticleController {
    def springSecurityService

    @Secured(['ROLE_PREMIUM_USER'])
    def listPremium() { 
        render 'premium content'
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的单元测试中,我想测试具有角色'ROLE_PREMIUM_USER'的用户是否可以看到listPremium方法的内容.我怎样才能做到这一点?

我知道它应该从如下开始:

@TestFor(ArticleController)
@Mock([SpringSecurityService])
class ArticleControllerTests {
    void testListPremium() {
    defineBeans {
        springSecurityService(SpringSecurityService)
    }
         //but how to login the user here in order to see premium content?

        controller.listPremium()
        assert response.text() == 'premium content'
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何验证检查ROLE_PREMIUM_USER的用户或模拟操作.有帮助吗?

chr*_*cnm 5

你也许可以使用

SpringSecurityUtils.reauthenticate username, null
Run Code Online (Sandbox Code Playgroud)