I have a working spring-security
configuration which wraps my jersey-based REST endpoints and allows method-level access.
Sample project with everything needed to reproduce the problem quickly: https://github.com/pulkitsinghal/dummy-rest-api
// Server-Side jersey resource
@GET
@Path("/protected/myendpoint/")
@PreAuthorize("hasRole('DUMMY')")
public String getMyEndpoint(){
return "blah";
}
But when writing sanity tests for the protected endpoint, I ran into the following exception which only occurs in the unit tests:
Caused by:
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException:
An Authentication object was not found in the SecurityContext
Here is what the JerseyTest based Unit Test class looks like:
@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);
}
Has anyone else run into this problem when setting up a JerseyTest
for a spring-security protected endpoint? What can be done about it?
I remotely see some connection here: Spring Test & Security: How to mock authentication? but I am not at a level where I could make heads or tails of what's going on in that thread. Thoughts?