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

时间:2012-05-08 23:15:33

标签: 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'
    }
}

在我的单元测试中,我想测试具有角色'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'
    }
}

我不确定如何验证检查ROLE_PREMIUM_USER的用户或模拟操作。有什么帮助吗?

2 个答案:

答案 0 :(得分:5)

您可以使用

SpringSecurityUtils.reauthenticate username, null

答案 1 :(得分:4)

我们创建了自定义AuthenticationHelper:

public final class AuthenticationHelper {

    public static Authentication authenticate(UserDetailsService userDetailsServiceImpl, String userName) {

        UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(userName);

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword());

        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(userDetails, token.getCredentials(), userDetails.getAuthorities());
        result.setDetails(token.getDetails());
        Authentication auth = result;

        SecurityContextHolder.getContext().setAuthentication(auth);
        auth = SecurityContextHolder.getContext().getAuthentication();

        Assert.assertTrue(auth.isAuthenticated());

        return auth;
    }
}

重要的部分是:

SecurityContextHolder.getContext().setAuthentication(auth);