【发布时间】:2013-11-12 20:15:11
【问题描述】:
我有一个有效的 spring-security 配置,它包装了我基于球衣的 REST 端点并允许方法级访问。
包含快速重现问题所需的一切的示例项目:https://github.com/pulkitsinghal/dummy-rest-api
// Server-Side jersey resource
@GET
@Path("/protected/myendpoint/")
@PreAuthorize("hasRole('DUMMY')")
public String getMyEndpoint(){
return "blah";
}
但在为受保护端点编写健全性测试时,我遇到了以下异常仅在单元测试中发生:
Caused by:
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException:
An Authentication object was not found in the SecurityContext
下面是基于 JerseyTest 的单元测试类的样子:
@Test
public void testProtectedEndpoint() {
WebResource webResource = resource();
webResource.addFilter(new HTTPBasicAuthFilter("username", "password"));
String responseMsg = webResource
.path("protected/myendpoint/")
.get(String.class);
System.out.println(responseMsg);
}
在为受弹簧安全保护的端点设置JerseyTest 时,有没有其他人遇到过这个问题?有什么办法呢?
我在这里远程看到了一些联系:Spring Test & Security: How to mock authentication?,但我还没有达到可以对该线程中正在发生的事情做出正面或反面的水平。想法?
【问题讨论】:
-
您能否发布异常的完整堆栈跟踪以及您的 Spring Security 配置?另外,您使用的是哪个版本的 Spring、Spring Security 和 Jersey?
-
添加了一个在运行单元测试时演示问题的工作示例项目,此处:github.com/pulkitsinghal/dummy-rest-api
-
这种单元测试是不是在
GrizzlyWebTestContainerFactory上不管用?