单元测试时防止AuthenticationCredentialsNotFoundException

时间:2014-01-31 22:54:46

标签: spring unit-testing spring-security

如何防止Spring Security在我的单元测试中抛出AuthenticationCredentialsNotFoundException?我希望用户不要进行身份验证,也不要匿名进行身份验证。

我试着这样做:

    SecurityContext ctx = SecurityContextHolder.createEmptyContext();
    SecurityContextHolder.setContext(ctx);
//  ctx.setAuthentication();

但我不知道从哪里获取匿名身份验证对象。

1 个答案:

答案 0 :(得分:4)

您的代码示例非常不明确。我假设您使用的是从Spring Security getting started page

获取的基本配置

要匿名验证用户,您需要将匿名用户放入安全上下文中:

SecurityContext ctx = SecurityContextHolder.createEmptyContext();
SecurityContextHolder.setContext(ctx);
ctx.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "", Arrays.asList(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))));

否则,您应该从相关网址中删除所有安全映射或注释。参见:

How do I get permitAll in Spring Security to NOT throw AuthenticationCredentialsNotFoundException in @Controller object?