There is a newer version available. Please update to Spring Security 5.6! |
Reactive Applications
WebFlux Security
Spring Security’s WebFlux support relies on a WebFilter
and works the same for Spring WebFlux and Spring WebFlux.Fn.
You can find a few sample applications that demonstrate the code below:
-
Hello WebFlux {gh-samples-url}/reactive/webflux/java/hello-security[hellowebflux]
-
Hello WebFlux.Fn {gh-samples-url}/reactive/webflux-fn/hello-security[hellowebfluxfn]
-
Hello WebFlux Method {gh-samples-url}/reactive/webflux/java/method[hellowebflux-method]
Minimal WebFlux Security Configuration
You can find a minimal WebFlux Security configuration below:
@EnableWebFluxSecurity
public class HelloWebfluxSecurityConfig {
@Bean
public MapReactiveUserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("user")
.roles("USER")
.build();
return new MapReactiveUserDetailsService(user);
}
}
@EnableWebFluxSecurity
class HelloWebfluxSecurityConfig {
@Bean
fun userDetailsService(): ReactiveUserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("user")
.roles("USER")
.build()
return MapReactiveUserDetailsService(userDetails)
}
}
This configuration provides form and http basic authentication, sets up authorization to require an authenticated user for accessing any page, sets up a default log in page and a default log out page, sets up security related HTTP headers, CSRF protection, and more.
Explicit WebFlux Security Configuration
You can find an explicit version of the minimal WebFlux Security configuration below:
@Configuration
@EnableWebFluxSecurity
public class HelloWebfluxSecurityConfig {
@Bean
public MapReactiveUserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("user")
.roles("USER")
.build();
return new MapReactiveUserDetailsService(user);
}
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange(exchanges -> exchanges
.anyExchange().authenticated()
)
.httpBasic(withDefaults())
.formLogin(withDefaults());
return http.build();
}
}
@Configuration
@EnableWebFluxSecurity
class HelloWebfluxSecurityConfig {
@Bean
fun userDetailsService(): ReactiveUserDetailsService {
val userDetails = User.withDefaultPasswordEncoder()
.username("user")
.password("user")
.roles("USER")
.build()
return MapReactiveUserDetailsService(userDetails)
}
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
authorizeExchange {
authorize(anyExchange, authenticated)
}
formLogin { }
httpBasic { }
}
}
}
This configuration explicitly sets up all the same things as our minimal configuration. From here you can easily make the changes to the defaults.
You can find more examples of explicit configuration in unit tests, by searching EnableWebFluxSecurity in the config/src/test/
directory.
Multiple Chains Support
You can configure multiple SecurityWebFilterChain
instances to separate configuration by RequestMatcher
s.
For example, you can isolate configuration for URLs that start with /api
, like so:
@Configuration
@EnableWebFluxSecurity
static class MultiSecurityHttpConfig {
@Order(Ordered.HIGHEST_PRECEDENCE) (1)
@Bean
SecurityWebFilterChain apiHttpSecurity(ServerHttpSecurity http) {
http
.securityMatcher(new PathPatternParserServerWebExchangeMatcher("/api/**")) (2)
.authorizeExchange((exchanges) -> exchanges
.anyExchange().authenticated()
)
.oauth2ResourceServer(OAuth2ResourceServerSpec::jwt); (3)
return http.build();
}
@Bean
SecurityWebFilterChain webHttpSecurity(ServerHttpSecurity http) { (4)
http
.authorizeExchange((exchanges) -> exchanges
.anyExchange().authenticated()
)
.httpBasic(withDefaults()) (5)
return http.build();
}
@Bean
ReactiveUserDetailsService userDetailsService() {
return new MapReactiveUserDetailsService(
PasswordEncodedUser.user(), PasswordEncodedUser.admin());
}
}
1 | Configure a SecurityWebFilterChain with an @Order to specify which SecurityWebFilterChain Spring Security should consider first |
2 | Use PathPatternParserServerWebExchangeMatcher to state that this SecurityWebFilterChain will only apply to URL paths that start with /api/ |
3 | Specify the authentication mechanisms that will be used for /api/** endpoints |
4 | Create another instance of SecurityWebFilterChain with lower precedence to match all other URLs |
5 | Specify the authentication mechanisms that will be used for the rest of the application |
Spring Security will select one SecurityWebFilterChain
@Bean
for each request.
It will match the requests in order by the securityMatcher
definition.
In this case, that means that if the URL path starts with /api
, then Spring Security will use apiHttpSecurity
.
If the URL does not start with /api
then Spring Security will default to webHttpSecurity
, which has an implied securityMatcher
that matches any request.
Unresolved include directive in modules/ROOT/pages/reactive/index.adoc - include::exploits/index.adoc[]
Unresolved include directive in modules/ROOT/pages/reactive/index.adoc - include::oauth2/index.adoc[]
@RegisteredOAuth2AuthorizedClient
Spring Security allows resolving an access token using @RegisteredOAuth2AuthorizedClient
.
A working example can be found in {gh-samples-url}/reactive/webflux/java/oauth2/webclient[OAuth 2.0 WebClient WebFlux sample]. |
After configuring Spring Security for OAuth2 Login or as an OAuth2 Client, an OAuth2AuthorizedClient
can be resolved using the following:
@GetMapping("/explicit")
Mono<String> explicit(@RegisteredOAuth2AuthorizedClient("client-id") OAuth2AuthorizedClient authorizedClient) {
// ...
}
@GetMapping("/explicit")
fun explicit(@RegisteredOAuth2AuthorizedClient("client-id") authorizedClient: OAuth2AuthorizedClient?): Mono<String> {
// ...
}
This integrates into Spring Security to provide the following features:
-
Spring Security will automatically refresh expired tokens (if a refresh token is present)
-
If an access token is requested and not present, Spring Security will automatically request the access token.
-
For
authorization_code
this involves performing the redirect and then replaying the original request -
For
client_credentials
the token is simply requested and saved
-
If the user authenticated using oauth2Login()
, then the client-id
is optional.
For example, the following would work:
@GetMapping("/implicit")
Mono<String> implicit(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient) {
// ...
}
@GetMapping("/implicit")
fun implicit(@RegisteredOAuth2AuthorizedClient authorizedClient: OAuth2AuthorizedClient?): Mono<String> {
// ...
}
This is convenient if the user always authenticates with OAuth2 Login and an access token from the same authorization server is needed.
Reactive X.509 Authentication
Similar to Servlet X.509 authentication, reactive x509 authentication filter allows extracting an authentication token from a certificate provided by a client.
Below is an example of a reactive x509 security configuration:
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
http
.x509(withDefaults())
.authorizeExchange(exchanges -> exchanges
.anyExchange().permitAll()
);
return http.build();
}
In the configuration above, when neither principalExtractor
nor authenticationManager
is provided defaults will be used. The default principal extractor is SubjectDnX509PrincipalExtractor
which extracts the CN (common name) field from a certificate provided by a client. The default authentication manager is ReactivePreAuthenticatedAuthenticationManager
which performs user account validation, checking that user account with a name extracted by principalExtractor
exists and it is not locked, disabled, or expired.
The next example demonstrates how these defaults can be overridden.
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
SubjectDnX509PrincipalExtractor principalExtractor =
new SubjectDnX509PrincipalExtractor();
principalExtractor.setSubjectDnRegex("OU=(.*?)(?:,|$)");
ReactiveAuthenticationManager authenticationManager = authentication -> {
authentication.setAuthenticated("Trusted Org Unit".equals(authentication.getName()));
return Mono.just(authentication);
};
http
.x509(x509 -> x509
.principalExtractor(principalExtractor)
.authenticationManager(authenticationManager)
)
.authorizeExchange(exchanges -> exchanges
.anyExchange().authenticated()
);
return http.build();
}
In this example, a username is extracted from the OU field of a client certificate instead of CN, and account lookup using ReactiveUserDetailsService
is not performed at all. Instead, if the provided certificate issued to an OU named "Trusted Org Unit", a request will be authenticated.
For an example of configuring Netty and WebClient
or curl
command-line tool to use mutual TLS and enable X.509 authentication, please refer to https://github.com/spring-projects/spring-security-samples/tree/main/servlet/java-configuration/authentication/x509.
WebClient
The following documentation is for use within Reactive environments. For Servlet environments, refer to WebClient for Servlet environments. |
Spring Framework has built in support for setting a Bearer token.
webClient.get()
.headers(h -> h.setBearerAuth(token))
...
webClient.get()
.headers { it.setBearerAuth(token) }
...
Spring Security builds on this support to provide additional benefits:
-
Spring Security will automatically refresh expired tokens (if a refresh token is present)
-
If an access token is requested and not present, Spring Security will automatically request the access token.
-
For authorization_code this involves performing the redirect and then replaying the original request
-
For client_credentials the token is simply requested and saved
-
-
Support for the ability to transparently include the current OAuth token or explicitly select which token should be used.
WebClient OAuth2 Setup
The first step is ensuring to setup the WebClient
correctly.
An example of setting up WebClient
in a fully reactive environment can be found below:
@Bean
WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations,
ServerOAuth2AuthorizedClientRepository authorizedClients) {
ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
new ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients);
// (optional) explicitly opt into using the oauth2Login to provide an access token implicitly
// oauth.setDefaultOAuth2AuthorizedClient(true);
// (optional) set a default ClientRegistration.registrationId
// oauth.setDefaultClientRegistrationId("client-registration-id");
return WebClient.builder()
.filter(oauth)
.build();
}
@Bean
fun webClient(clientRegistrations: ReactiveClientRegistrationRepository,
authorizedClients: ServerOAuth2AuthorizedClientRepository): WebClient {
val oauth = ServerOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients)
// (optional) explicitly opt into using the oauth2Login to provide an access token implicitly
// oauth.setDefaultOAuth2AuthorizedClient(true)
// (optional) set a default ClientRegistration.registrationId
// oauth.setDefaultClientRegistrationId("client-registration-id")
return WebClient.builder()
.filter(oauth)
.build()
}
Implicit OAuth2AuthorizedClient
If we set defaultOAuth2AuthorizedClient
to true
in our setup and the user authenticated with oauth2Login (i.e. OIDC), then the current authentication is used to automatically provide the access token.
Alternatively, if we set defaultClientRegistrationId
to a valid ClientRegistration
id, that registration is used to provide the access token.
This is convenient, but in environments where not all endpoints should get the access token, it is dangerous (you might provide the wrong access token to an endpoint).
Mono<String> body = this.webClient
.get()
.uri(this.uri)
.retrieve()
.bodyToMono(String.class);
val body: Mono<String> = webClient
.get()
.uri(this.uri)
.retrieve()
.bodyToMono()
Explicit OAuth2AuthorizedClient
The OAuth2AuthorizedClient
can be explicitly provided by setting it on the requests attributes.
In the example below we resolve the OAuth2AuthorizedClient
using Spring WebFlux or Spring MVC argument resolver support.
However, it does not matter how the OAuth2AuthorizedClient
is resolved.
@GetMapping("/explicit")
Mono<String> explicit(@RegisteredOAuth2AuthorizedClient("client-id") OAuth2AuthorizedClient authorizedClient) {
return this.webClient
.get()
.uri(this.uri)
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono(String.class);
}
@GetMapping("/explicit")
fun explicit(@RegisteredOAuth2AuthorizedClient("client-id") authorizedClient: OAuth2AuthorizedClient?): Mono<String> {
return this.webClient
.get()
.uri(uri)
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono()
}
clientRegistrationId
Alternatively, it is possible to specify the clientRegistrationId
on the request attributes and the WebClient
will attempt to lookup the OAuth2AuthorizedClient
.
If it is not found, one will automatically be acquired.
Mono<String> body = this.webClient
.get()
.uri(this.uri)
.attributes(clientRegistrationId("client-id"))
.retrieve()
.bodyToMono(String.class);
val body: Mono<String> = this.webClient
.get()
.uri(uri)
.attributes(clientRegistrationId("client-id"))
.retrieve()
.bodyToMono()
EnableReactiveMethodSecurity
Spring Security supports method security using Reactor’s Context which is setup using ReactiveSecurityContextHolder
.
For example, this demonstrates how to retrieve the currently logged in user’s message.
For this to work the return type of the method must be a |
Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
Mono<String> messageByUsername = ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.map(Authentication::getName)
.flatMap(this::findMessageByUsername)
// In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter`
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
StepVerifier.create(messageByUsername)
.expectNext("Hi user")
.verifyComplete();
val authentication: Authentication = TestingAuthenticationToken("user", "password", "ROLE_USER")
val messageByUsername: Mono<String> = ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.map(Authentication::getName)
.flatMap(this::findMessageByUsername) // In a WebFlux application the `subscriberContext` is automatically setup using `ReactorContextWebFilter`
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication))
StepVerifier.create(messageByUsername)
.expectNext("Hi user")
.verifyComplete()
with this::findMessageByUsername
defined as:
Mono<String> findMessageByUsername(String username) {
return Mono.just("Hi " + username);
}
fun findMessageByUsername(username: String): Mono<String> {
return Mono.just("Hi $username")
}
Below is a minimal method security configuration when using method security in reactive applications.
@EnableReactiveMethodSecurity
public class SecurityConfig {
@Bean
public MapReactiveUserDetailsService userDetailsService() {
User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
UserDetails rob = userBuilder.username("rob")
.password("rob")
.roles("USER")
.build();
UserDetails admin = userBuilder.username("admin")
.password("admin")
.roles("USER","ADMIN")
.build();
return new MapReactiveUserDetailsService(rob, admin);
}
}
@EnableReactiveMethodSecurity
class SecurityConfig {
@Bean
fun userDetailsService(): MapReactiveUserDetailsService {
val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
val rob = userBuilder.username("rob")
.password("rob")
.roles("USER")
.build()
val admin = userBuilder.username("admin")
.password("admin")
.roles("USER", "ADMIN")
.build()
return MapReactiveUserDetailsService(rob, admin)
}
}
Consider the following class:
@Component
public class HelloWorldMessageService {
@PreAuthorize("hasRole('ADMIN')")
public Mono<String> findMessage() {
return Mono.just("Hello World!");
}
}
@Component
class HelloWorldMessageService {
@PreAuthorize("hasRole('ADMIN')")
fun findMessage(): Mono<String> {
return Mono.just("Hello World!")
}
}
Or, the following class using Kotlin coroutines:
@Component
class HelloWorldMessageService {
@PreAuthorize("hasRole('ADMIN')")
suspend fun findMessage(): String {
delay(10)
return "Hello World!"
}
}
Combined with our configuration above, @PreAuthorize("hasRole('ADMIN')")
will ensure that findByMessage
is only invoked by a user with the role ADMIN
.
It is important to note that any of the expressions in standard method security work for @EnableReactiveMethodSecurity
.
However, at this time we only support return type of Boolean
or boolean
of the expression.
This means that the expression must not block.
When integrating with WebFlux Security, the Reactor Context is automatically established by Spring Security according to the authenticated user.
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {
@Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
return http
// Demonstrate that method security works
// Best practice to use both for defense in depth
.authorizeExchange(exchanges -> exchanges
.anyExchange().permitAll()
)
.httpBasic(withDefaults())
.build();
}
@Bean
MapReactiveUserDetailsService userDetailsService() {
User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
UserDetails rob = userBuilder.username("rob")
.password("rob")
.roles("USER")
.build();
UserDetails admin = userBuilder.username("admin")
.password("admin")
.roles("USER","ADMIN")
.build();
return new MapReactiveUserDetailsService(rob, admin);
}
}
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
class SecurityConfig {
@Bean
open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
return http {
authorizeExchange {
authorize(anyExchange, permitAll)
}
httpBasic { }
}
}
@Bean
fun userDetailsService(): MapReactiveUserDetailsService {
val userBuilder: User.UserBuilder = User.withDefaultPasswordEncoder()
val rob = userBuilder.username("rob")
.password("rob")
.roles("USER")
.build()
val admin = userBuilder.username("admin")
.password("admin")
.roles("USER", "ADMIN")
.build()
return MapReactiveUserDetailsService(rob, admin)
}
}
You can find a complete sample in {gh-samples-url}/reactive/webflux/java/method[hellowebflux-method]
CORS
Spring Framework provides first class support for CORS.
CORS must be processed before Spring Security because the pre-flight request will not contain any cookies (i.e. the JSESSIONID
).
If the request does not contain any cookies and Spring Security is first, the request will determine the user is not authenticated (since there are no cookies in the request) and reject it.
The easiest way to ensure that CORS is handled first is to use the CorsWebFilter
.
Users can integrate the CorsWebFilter
with Spring Security by providing a CorsConfigurationSource
.
For example, the following will integrate CORS support within Spring Security:
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
The following will disable the CORS integration within Spring Security:
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.cors(cors -> cors.disable());
return http.build();
}
Reactive Test Support
Testing Reactive Method Security
For example, we can test our example from EnableReactiveMethodSecurity 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.
RSocket Security
Spring Security’s RSocket support relies on a SocketAcceptorInterceptor
.
The main entry point into security is found in the PayloadSocketAcceptorInterceptor
which adapts the RSocket APIs to allow intercepting a PayloadExchange
with PayloadInterceptor
implementations.
You can find a few sample applications that demonstrate the code below:
-
Hello RSocket {gh-samples-url}/reactive/rsocket/hello-security[hellorsocket]
Minimal RSocket Security Configuration
You can find a minimal RSocket Security configuration below:
@Configuration
@EnableRSocketSecurity
public class HelloRSocketSecurityConfig {
@Bean
public MapReactiveUserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("user")
.roles("USER")
.build();
return new MapReactiveUserDetailsService(user);
}
}
This configuration enables simple authentication and sets up rsocket-authorization to require an authenticated user for any request.
Adding SecuritySocketAcceptorInterceptor
For Spring Security to work we need to apply SecuritySocketAcceptorInterceptor
to the ServerRSocketFactory
.
This is what connects our PayloadSocketAcceptorInterceptor
we created with the RSocket infrastructure.
In a Spring Boot application this is done automatically using RSocketSecurityAutoConfiguration
with the following code.
@Bean
RSocketServerCustomizer springSecurityRSocketSecurity(SecuritySocketAcceptorInterceptor interceptor) {
return (server) -> server.interceptors((registry) -> registry.forSocketAcceptor(interceptor));
}
RSocket Authentication
RSocket authentication is performed with AuthenticationPayloadInterceptor
which acts as a controller to invoke a ReactiveAuthenticationManager
instance.
Authentication at Setup vs Request Time
Generally, authentication can occur at setup time and/or request time.
Authentication at setup time makes sense in a few scenarios. A common scenarios is when a single user (i.e. mobile connection) is leveraging an RSocket connection. In this case only a single user is leveraging the connection, so authentication can be done once at connection time.
In a scenario where the RSocket connection is shared it makes sense to send credentials on each request. For example, a web application that connects to an RSocket server as a downstream service would make a single connection that all users leverage. In this case, if the RSocket server needs to perform authorization based on the web application’s users credentials per request makes sense.
In some scenarios authentication at setup and per request makes sense.
Consider a web application as described previously.
If we need to restrict the connection to the web application itself, we can provide a credential with a SETUP
authority at connection time.
Then each user would have different authorities but not the SETUP
authority.
This means that individual users can make requests but not make additional connections.
Simple Authentication
Spring Security has support for Simple Authentication Metadata Extension.
Basic Authentication drafts evolved into Simple Authentication and is only supported for backward compatibility.
See |
The RSocket receiver can decode the credentials using AuthenticationPayloadExchangeConverter
which is automatically setup using the simpleAuthentication
portion of the DSL.
An explicit configuration can be found below.
@Bean
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
rsocket
.authorizePayload(authorize ->
authorize
.anyRequest().authenticated()
.anyExchange().permitAll()
)
.simpleAuthentication(Customizer.withDefaults());
return rsocket.build();
}
The RSocket sender can send credentials using SimpleAuthenticationEncoder
which can be added to Spring’s RSocketStrategies
.
RSocketStrategies.Builder strategies = ...;
strategies.encoder(new SimpleAuthenticationEncoder());
It can then be used to send a username and password to the receiver in the setup:
MimeType authenticationMimeType =
MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
Mono<RSocketRequester> requester = RSocketRequester.builder()
.setupMetadata(credentials, authenticationMimeType)
.rsocketStrategies(strategies.build())
.connectTcp(host, port);
Alternatively or additionally, a username and password can be sent in a request.
Mono<RSocketRequester> requester;
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
public Mono<AirportLocation> findRadar(String code) {
return this.requester.flatMap(req ->
req.route("find.radar.{code}", code)
.metadata(credentials, authenticationMimeType)
.retrieveMono(AirportLocation.class)
);
}
JWT
Spring Security has support for Bearer Token Authentication Metadata Extension. The support comes in the form of authenticating a JWT (determining the JWT is valid) and then using the JWT to make authorization decisions.
The RSocket receiver can decode the credentials using BearerPayloadExchangeConverter
which is automatically setup using the jwt
portion of the DSL.
An example configuration can be found below:
@Bean
PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
rsocket
.authorizePayload(authorize ->
authorize
.anyRequest().authenticated()
.anyExchange().permitAll()
)
.jwt(Customizer.withDefaults());
return rsocket.build();
}
The configuration above relies on the existence of a ReactiveJwtDecoder
@Bean
being present.
An example of creating one from the issuer can be found below:
@Bean
ReactiveJwtDecoder jwtDecoder() {
return ReactiveJwtDecoders
.fromIssuerLocation("https://example.com/auth/realms/demo");
}
The RSocket sender does not need to do anything special to send the token because the value is just a simple String. For example, the token can be sent at setup time:
MimeType authenticationMimeType =
MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());
BearerTokenMetadata token = ...;
Mono<RSocketRequester> requester = RSocketRequester.builder()
.setupMetadata(token, authenticationMimeType)
.connectTcp(host, port);
Alternatively or additionally, the token can be sent in a request.
MimeType authenticationMimeType =
MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());
Mono<RSocketRequester> requester;
BearerTokenMetadata token = ...;
public Mono<AirportLocation> findRadar(String code) {
return this.requester.flatMap(req ->
req.route("find.radar.{code}", code)
.metadata(token, authenticationMimeType)
.retrieveMono(AirportLocation.class)
);
}
RSocket Authorization
RSocket authorization is performed with AuthorizationPayloadInterceptor
which acts as a controller to invoke a ReactiveAuthorizationManager
instance.
The DSL can be used to setup authorization rules based upon the PayloadExchange
.
An example configuration can be found below:
rsocket .authorizePayload(authorize -> authz .setup().hasRole("SETUP") (1) .route("fetch.profile.me").authenticated() (2) .matcher(payloadExchange -> isMatch(payloadExchange)) (3) .hasRole("CUSTOM") .route("fetch.profile.{username}") (4) .access((authentication, context) -> checkFriends(authentication, context)) .anyRequest().authenticated() (5) .anyExchange().permitAll() (6) )
1 | Setting up a connection requires the authority ROLE_SETUP |
2 | If the route is fetch.profile.me authorization only requires the user be authenticated |
3 | In this rule we setup a custom matcher where authorization requires the user to have the authority ROLE_CUSTOM |
4 | This rule leverages custom authorization.
The matcher expresses a variable with the name username that is made available in the context .
A custom authorization rule is exposed in the checkFriends method. |
5 | This rule ensures that request that does not already have a rule will require the user to be authenticated. A request is where the metadata is included. It would not include additional payloads. |
6 | This rule ensures that any exchange that does not already have a rule is allowed for anyone. In this example, it means that payloads that have no metadata have no authorization rules. |
It is important to understand that authorization rules are performed in order. Only the first authorization rule that matches will be invoked.