What is the best way to run Spring Boot integration tests agains a OAuth Resource server configured web application.
I can think of two theoretical approaches:
- Mock the security context in the resource server without acutally calling the Authorization server.
- Embed the Authorization server as part of the test and redirect the authentication to it.
I was wondering how others have approach this problem.
I use spring security 4.x
@WithSecurityContext('user')
annotation to create mockSecurityContext
with'user'
logged in. Then when calling my REST API usingMockMvc
I retrieveSecurityContext
and attach it to the call.Like this:
where
security()
is static method:So using
@WithSecurityContext('user')
mockSecurityContext
with authenticated user with login'user'
is created for my test method. Then in that method I retrieve this mockSecurityContext
and attach it to the REST API call to make my oAuth think user is allready authenticated. It's basically the first approach you suggested in your question.For this to work you must switch your OAuth to be statefull for the tests. Otherwise it won't work.
ie like this:
You see my
stateless
property which gets injected only in tests. In normal run it uses it's default valuetrue
(so it's stateless). For tests I declareoauth2StatelessSecurityContext
Bean with valuefalse
so it turns statefull for tests.I define this configuration for tests:
That's how I did it. I hope my explanation is understandable.
This answer is very similar to the one provided by Ondrej, but is quite a bit simpler.
Spring Security 4 provides Test support. To use it ensure you have spring-security-test-4.0.2.RELEASE.jar (or newer version on your classpath). You will also want to ensure you are working with spring-test-4.1.0.RELEASE (or newer).
Next you can use MockMvc as the other answer indicates. However, if you setup MockMvc with the following:
This makes it so
In short, you should be able to do something like this:
I'd encourage you to read through the rest of the Spring Security Testing section of the reference as it provides lots of additional details including how to use custom authentication.