There is a newer version available. Please update to Spring Security 5.6! |
Reactive Test Support
Testing Reactive Method Security
For example, we can test our example from [jc-erms] using the same setup and annotations we did in [test-method]. Here is a minimal sample of what we can do:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = HelloWebfluxMethodApplication.class)
public class HelloWorldMessageServiceTests {
@Autowired
HelloWorldMessageService messages;
@Test
public void messagesWhenNotAuthenticatedThenDenied() {
StepVerifier.create(this.messages.findMessage())
.expectError(AccessDeniedException.class)
.verify();
}
@Test
@WithMockUser
public void messagesWhenUserThenDenied() {
StepVerifier.create(this.messages.findMessage())
.expectError(AccessDeniedException.class)
.verify();
}
@Test
@WithMockUser(roles = "ADMIN")
public void messagesWhenAdminThenOk() {
StepVerifier.create(this.messages.findMessage())
.expectNext("Hello World!")
.verifyComplete();
}
}
WebTestClientSupport
Spring Security provides integration with WebTestClient
.
The basic setup looks like this:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = HelloWebfluxMethodApplication.class)
public class HelloWebfluxMethodApplicationTests {
@Autowired
ApplicationContext context;
WebTestClient rest;
@Before
public void setup() {
this.rest = WebTestClient
.bindToApplicationContext(this.context)
// add Spring Security test Support
.apply(springSecurity())
.configureClient()
.filter(basicAuthentication())
.build();
}
// ...
}
Authentication
After applying the Spring Security support to WebTestClient
we can use either annotations or mutateWith
support.
For example:
@Test
public void messageWhenNotAuthenticated() throws Exception {
this.rest
.get()
.uri("/message")
.exchange()
.expectStatus().isUnauthorized();
}
// --- WithMockUser ---
@Test
@WithMockUser
public void messageWhenWithMockUserThenForbidden() throws Exception {
this.rest
.get()
.uri("/message")
.exchange()
.expectStatus().isEqualTo(HttpStatus.FORBIDDEN);
}
@Test
@WithMockUser(roles = "ADMIN")
public void messageWhenWithMockAdminThenOk() throws Exception {
this.rest
.get()
.uri("/message")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello World!");
}
// --- mutateWith mockUser ---
@Test
public void messageWhenMutateWithMockUserThenForbidden() throws Exception {
this.rest
.mutateWith(mockUser())
.get()
.uri("/message")
.exchange()
.expectStatus().isEqualTo(HttpStatus.FORBIDDEN);
}
@Test
public void messageWhenMutateWithMockAdminThenOk() throws Exception {
this.rest
.mutateWith(mockUser().roles("ADMIN"))
.get()
.uri("/message")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello World!");
}
CSRF Support
Spring Security also provides support for CSRF testing with WebTestClient
.
For example:
this.rest
// provide a valid CSRF token
.mutateWith(csrf())
.post()
.uri("/login")
...
Testing OAuth 2.0
When it comes to OAuth 2.0, the same principles covered earlier still apply: Ultimately, it depends on what your method under test is expecting to be in the SecurityContextHolder
.
For example, for a controller that looks like this:
@GetMapping("/endpoint")
public Mono<String> foo(Principal user) {
return Mono.just(user.getName());
}
There’s nothing OAuth2-specific about it, so you will likely be able to simply use @WithMockUser
and be fine.
But, in cases where your controllers are bound to some aspect of Spring Security’s OAuth 2.0 support, like the following:
@GetMapping("/endpoint")
public Mono<String> foo(@AuthenticationPrincipal OidcUser user) {
return Mono.just(user.getIdToken().getSubject());
}
then Spring Security’s test support can come in handy.
Testing OIDC Login
Testing the method above with WebTestClient
would require simulating some kind of grant flow with an authorization server.
Certainly this would be a daunting task, which is why Spring Security ships with support for removing this boilerplate.
For example, we can tell Spring Security to include a default OidcUser
using the SecurityMockServerConfigurers#oidcLogin
method, like so:
client
.mutateWith(mockOidcLogin()).get().uri("/endpoint").exchange();
What this will do is configure the associated MockServerRequest
with an OidcUser
that includes a simple OidcIdToken
, OidcUserInfo
, and Collection
of granted authorities.
Specifically, it will include an OidcIdToken
with a sub
claim set to user
:
assertThat(user.getIdToken().getClaim("sub")).isEqualTo("user");
an OidcUserInfo
with no claims set:
assertThat(user.getUserInfo().getClaims()).isEmpty();
and a Collection
of authorities with just one authority, SCOPE_read
:
assertThat(user.getAuthorities()).hasSize(1);
assertThat(user.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));
Spring Security does the necessary work to make sure that the OidcUser
instance is available for the @AuthenticationPrincipal
annotation.
Further, it also links that OidcUser
to a simple instance of OAuth2AuthorizedClient
that it deposits into a mock ServerOAuth2AuthorizedClientRepository
.
This can be handy if your tests use the @RegisteredOAuth2AuthorizedClient
annotation..
Configuring Authorities
In many circumstances, your method is protected by filter or method security and needs your Authentication
to have certain granted authorities to allow the request.
In this case, you can supply what granted authorities you need using the authorities()
method:
client
.mutateWith(mockOidcLogin()
.authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
)
.get().uri("/endpoint").exchange();
Configuring Claims
And while granted authorities are quite common across all of Spring Security, we also have claims in the case of OAuth 2.0.
Let’s say, for example, that you’ve got a user_id
claim that indicates the user’s id in your system.
You might access it like so in a controller:
@GetMapping("/endpoint")
public Mono<String> foo(@AuthenticationPrincipal OidcUser oidcUser) {
String userId = oidcUser.getIdToken().getClaim("user_id");
// ...
}
In that case, you’d want to specify that claim with the idToken()
method:
client
.mutateWith(mockOidcLogin()
.idToken(token -> token.claim("user_id", "1234"))
)
.get().uri("/endpoint").exchange();
since OidcUser
collects its claims from OidcIdToken
.
Additional Configurations
There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects:
-
userInfo(OidcUserInfo.Builder)
- For configuring theOidcUserInfo
instance -
clientRegistration(ClientRegistration)
- For configuring the associatedOAuth2AuthorizedClient
with a givenClientRegistration
-
oidcUser(OidcUser)
- For configuring the completeOidcUser
instance
That last one is handy if you:
1. Have your own implementation of OidcUser
, or
2. Need to change the name attribute
For example, let’s say that your authorization server sends the principal name in the user_name
claim instead of the sub
claim.
In that case, you can configure an OidcUser
by hand:
OidcUser oidcUser = new DefaultOidcUser(
AuthorityUtils.createAuthorityList("SCOPE_message:read"),
Collections.singletonMap("user_name", "foo_user"),
"user_name");
client
.mutateWith(mockOidcLogin().oidcUser(oidcUser))
.get().uri("/endpoint").exchange();
Testing OAuth 2.0 Login
As with testing OIDC login, testing OAuth 2.0 Login presents a similar challenge of mocking a grant flow. And because of that, Spring Security also has test support for non-OIDC use cases.
Let’s say that we’ve got a controller that gets the logged-in user as an OAuth2User
:
@GetMapping("/endpoint")
public Mono<String> foo(@AuthenticationPrincipal OAuth2User oauth2User) {
return Mono.just(oauth2User.getAttribute("sub"));
}
In that case, we can tell Spring Security to include a default OAuth2User
using the SecurityMockServerConfigurers#oauth2User
method, like so:
client
.mutateWith(mockOAuth2Login())
.get().uri("/endpoint").exchange();
What this will do is configure the associated MockServerRequest
with an OAuth2User
that includes a simple Map
of attributes and Collection
of granted authorities.
Specifically, it will include a Map
with a key/value pair of sub
/user
:
assertThat((String) user.getAttribute("sub")).isEqualTo("user");
and a Collection
of authorities with just one authority, SCOPE_read
:
assertThat(user.getAuthorities()).hasSize(1);
assertThat(user.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));
Spring Security does the necessary work to make sure that the OAuth2User
instance is available for the @AuthenticationPrincipal
annotation.
Further, it also links that OAuth2User
to a simple instance of OAuth2AuthorizedClient
that it deposits in a mock ServerOAuth2AuthorizedClientRepository
.
This can be handy if your tests use the @RegisteredOAuth2AuthorizedClient
annotation.
Configuring Authorities
In many circumstances, your method is protected by filter or method security and needs your Authentication
to have certain granted authorities to allow the request.
In this case, you can supply what granted authorities you need using the authorities()
method:
client
.mutateWith(mockOAuth2Login()
.authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
)
.get().uri("/endpoint").exchange();
Configuring Claims
And while granted authorities are quite common across all of Spring Security, we also have claims in the case of OAuth 2.0.
Let’s say, for example, that you’ve got a user_id
attribute that indicates the user’s id in your system.
You might access it like so in a controller:
@GetMapping("/endpoint")
public Mono<String> foo(@AuthenticationPrincipal OAuth2User oauth2User) {
String userId = oauth2User.getAttribute("user_id");
// ...
}
In that case, you’d want to specify that attribute with the attributes()
method:
client
.mutateWith(mockOAuth2Login()
.attributes(attrs -> attrs.put("user_id", "1234"))
)
.get().uri("/endpoint").exchange();
Additional Configurations
There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects:
-
clientRegistration(ClientRegistration)
- For configuring the associatedOAuth2AuthorizedClient
with a givenClientRegistration
-
oauth2User(OAuth2User)
- For configuring the completeOAuth2User
instance
That last one is handy if you:
1. Have your own implementation of OAuth2User
, or
2. Need to change the name attribute
For example, let’s say that your authorization server sends the principal name in the user_name
claim instead of the sub
claim.
In that case, you can configure an OAuth2User
by hand:
OAuth2User oauth2User = new DefaultOAuth2User(
AuthorityUtils.createAuthorityList("SCOPE_message:read"),
Collections.singletonMap("user_name", "foo_user"),
"user_name");
client
.mutateWith(mockOAuth2Login().oauth2User(oauth2User))
.get().uri("/endpoint").exchange();
Testing OAuth 2.0 Clients
Independent of how your user authenticates, you may have other tokens and client registrations that are in play for the request you are testing. For example, your controller may be relying on the client credentials grant to get a token that isn’t associated with the user at all:
@GetMapping("/endpoint")
public Mono<String> foo(@RegisteredOAuth2AuthorizedClient("my-app") OAuth2AuthorizedClient authorizedClient) {
return this.webClient.get()
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono(String.class);
}
Simulating this handshake with the authorization server could be cumbersome.
Instead, you can use SecurityMockServerConfigurers#oauth2Client
to add a OAuth2AuthorizedClient
into a mock ServerOAuth2AuthorizedClientRepository
:
client
.mutateWith(mockOAuth2Client("my-app"))
.get().uri("/endpoint").exchange();
What this will do is create an OAuth2AuthorizedClient
that has a simple ClientRegistration
, OAuth2AccessToken
, and resource owner name.
Specifically, it will include a ClientRegistration
with a client id of "test-client" and client secret of "test-secret":
assertThat(authorizedClient.getClientRegistration().getClientId()).isEqualTo("test-client");
assertThat(authorizedClient.getClientRegistration().getClientSecret()).isEqualTo("test-secret");
a resource owner name of "user":
assertThat(authorizedClient.getPrincipalName()).isEqualTo("user");
and an OAuth2AccessToken
with just one scope, read
:
assertThat(authorizedClient.getAccessToken().getScopes()).hasSize(1);
assertThat(authorizedClient.getAccessToken().getScopes()).containsExactly("read");
The client can then be retrieved as normal using @RegisteredOAuth2AuthorizedClient
in a controller method.
Configuring Scopes
In many circumstances, the OAuth 2.0 access token comes with a set of scopes. If your controller inspects these, say like so:
@GetMapping("/endpoint")
public Mono<String> foo(@RegisteredOAuth2AuthorizedClient("my-app") OAuth2AuthorizedClient authorizedClient) {
Set<String> scopes = authorizedClient.getAccessToken().getScopes();
if (scopes.contains("message:read")) {
return this.webClient.get()
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono(String.class);
}
// ...
}
then you can configure the scope using the accessToken()
method:
client
.mutateWith(mockOAuth2Client("my-app")
.accessToken(new OAuth2AccessToken(BEARER, "token", null, null, Collections.singleton("message:read"))))
)
.get().uri("/endpoint").exchange();
Additional Configurations
There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects:
-
principalName(String)
- For configuring the resource owner name -
clientRegistration(Consumer<ClientRegistration.Builder>)
- For configuring the associatedClientRegistration
-
clientRegistration(ClientRegistration)
- For configuring the completeClientRegistration
That last one is handy if you want to use a real ClientRegistration
For example, let’s say that you are wanting to use one of your app’s ClientRegistration
definitions, as specified in your application.yml
.
In that case, your test can autowire the ReactiveClientRegistrationRepository
and look up the one your test needs:
@Autowired
ReactiveClientRegistrationRepository clientRegistrationRepository;
// ...
client
.mutateWith(mockOAuth2Client()
.clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook"))
)
.get().uri("/exchange").exchange();
Testing JWT Authentication
In order to make an authorized request on a resource server, you need a bearer token. If your resource server is configured for JWTs, then this would mean that the bearer token needs to be signed and then encoded according to the JWT specification. All of this can be quite daunting, especially when this isn’t the focus of your test.
Fortunately, there are a number of simple ways that you can overcome this difficulty and allow your tests to focus on authorization and not on representing bearer tokens. We’ll look at two of them now:
mockJwt() WebTestClientConfigurer
The first way is via a WebTestClientConfigurer
.
The simplest of these would look something like this:
client
.mutateWith(mockJwt()).get().uri("/endpoint").exchange();
What this will do is create a mock Jwt
, passing it correctly through any authentication APIs so that it’s available for your authorization mechanisms to verify.
By default, the JWT
that it creates has the following characteristics:
{
"headers" : { "alg" : "none" },
"claims" : {
"sub" : "user",
"scope" : "read"
}
}
And the resulting Jwt
, were it tested, would pass in the following way:
assertThat(jwt.getTokenValue()).isEqualTo("token");
assertThat(jwt.getHeaders().get("alg")).isEqualTo("none");
assertThat(jwt.getSubject()).isEqualTo("sub");
GrantedAuthority authority = jwt.getAuthorities().iterator().next();
assertThat(authority.getAuthority()).isEqualTo("read");
These values can, of course be configured.
Any headers or claims can be configured with their corresponding methods:
client
.mutateWith(mockJwt().jwt(jwt -> jwt.header("kid", "one")
.claim("iss", "https://idp.example.org")))
.get().uri("/endpoint").exchange();
client
.mutateWith(mockJwt().jwt(jwt -> jwt.claims(claims -> claims.remove("scope"))))
.get().uri("/endpoint").exchange();
The scope
and scp
claims are processed the same way here as they are in a normal bearer token request.
However, this can be overridden simply by providing the list of GrantedAuthority
instances that you need for your test:
client
.mutateWith(jwt().authorities(new SimpleGrantedAuthority("SCOPE_messages")))
.get().uri("/endpoint").exchange();
Or, if you have a custom Jwt
to Collection<GrantedAuthority>
converter, you can also use that to derive the authorities:
client
.mutateWith(jwt().authorities(new MyConverter()))
.get().uri("/endpoint").exchange();
You can also specify a complete Jwt
, for which {security-api-url}org/springframework/security/oauth2/jwt/Jwt.Builder.html[Jwt.Builder]
comes quite handy:
Jwt jwt = Jwt.withTokenValue("token")
.header("alg", "none")
.claim("sub", "user")
.claim("scope", "read");
client
.mutateWith(mockJwt().jwt(jwt))
.get().uri("/endpoint").exchange();
authentication()
WebTestClientConfigurer
The second way is by using the authentication()
Mutator
.
Essentially, you can instantiate your own JwtAuthenticationToken
and provide it in your test, like so:
Jwt jwt = Jwt.withTokenValue("token")
.header("alg", "none")
.claim("sub", "user")
.build();
Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("SCOPE_read");
JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities);
client
.mutateWith(authentication(token))
.get().uri("/endpoint").exchange();
Note that as an alternative to these, you can also mock the ReactiveJwtDecoder
bean itself with a @MockBean
annotation.
Testing Opaque Token Authentication
Similar to JWTs, opaque tokens require an authorization server in order to verify their validity, which can make testing more difficult. To help with that, Spring Security has test support for opaque tokens.
Let’s say that we’ve got a controller that retrieves the authentication as a BearerTokenAuthentication
:
@GetMapping("/endpoint")
public Mono<String> foo(BearerTokenAuthentication authentication) {
return Mono.just((String) authentication.getTokenAttributes("sub"));
}
In that case, we can tell Spring Security to include a default BearerTokenAuthentication
using the SecurityMockServerConfigurers#opaqueToken
method, like so:
client
.mutateWith(mockOpaqueToken())
.get().uri("/endpoint").exchange();
What this will do is configure the associated MockHttpServletRequest
with a BearerTokenAuthentication
that includes a simple OAuth2AuthenticatedPrincipal
, Map
of attributes, and Collection
of granted authorities.
Specifically, it will include a Map
with a key/value pair of sub
/user
:
assertThat((String) token.getTokenAttributes().get("sub")).isEqualTo("user");
and a Collection
of authorities with just one authority, SCOPE_read
:
assertThat(token.getAuthorities()).hasSize(1);
assertThat(token.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));
Spring Security does the necessary work to make sure that the BearerTokenAuthentication
instance is available for your controller methods.
Configuring Authorities
In many circumstances, your method is protected by filter or method security and needs your Authentication
to have certain granted authorities to allow the request.
In this case, you can supply what granted authorities you need using the authorities()
method:
client
.mutateWith(mockOpaqueToken()
.authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
)
.get().uri("/endpoint").exchange();
Configuring Claims
And while granted authorities are quite common across all of Spring Security, we also have attributes in the case of OAuth 2.0.
Let’s say, for example, that you’ve got a user_id
attribute that indicates the user’s id in your system.
You might access it like so in a controller:
@GetMapping("/endpoint")
public Mono<String> foo(BearerTokenAuthentication authentication) {
String userId = (String) authentication.getTokenAttributes().get("user_id");
// ...
}
In that case, you’d want to specify that attribute with the attributes()
method:
client
.mutateWith(mockOpaqueToken()
.attributes(attrs -> attrs.put("user_id", "1234"))
)
.get().uri("/endpoint").exchange();
Additional Configurations
There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects.
One such is principal(OAuth2AuthenticatedPrincipal)
, which you can use to configure the complete OAuth2AuthenticatedPrincipal
instance that underlies the BearerTokenAuthentication
It’s handy if you:
1. Have your own implementation of OAuth2AuthenticatedPrincipal
, or
2. Want to specify a different principal name
For example, let’s say that your authorization server sends the principal name in the user_name
attribute instead of the sub
attribute.
In that case, you can configure an OAuth2AuthenticatedPrincipal
by hand:
Map<String, Object> attributes = Collections.singletonMap("user_name", "foo_user");
OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(
(String) attributes.get("user_name"),
attributes,
AuthorityUtils.createAuthorityList("SCOPE_message:read"));
client
.mutateWith(mockOpaqueToken().principal(principal))
.get().uri("/endpoint").exchange();
Note that as an alternative to using mockOpaqueToken()
test support, you can also mock the OpaqueTokenIntrospector
bean itself with a @MockBean
annotation.