There is a newer version available. Please update to Spring Security 5.6!

@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:

Java
@GetMapping("/explicit")
Mono<String> explicit(@RegisteredOAuth2AuthorizedClient("client-id") OAuth2AuthorizedClient authorizedClient) {
	// ...
}
Kotlin
@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:

Java
@GetMapping("/implicit")
Mono<String> implicit(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient) {
	// ...
}
Kotlin
@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.