From 0c12aeb7a196f8094e9b458e9cf4e48aac8f3b93 Mon Sep 17 00:00:00 2001 From: Steve Riesenberg Date: Fri, 5 Nov 2021 10:44:16 -0500 Subject: [PATCH] Revamp OAuth 2.0 Login Reactive documentation Related gh-8174 --- .../ROOT/pages/reactive/oauth2/login.adoc | 1246 +++++++++++++++-- 1 file changed, 1157 insertions(+), 89 deletions(-) diff --git a/docs/modules/ROOT/pages/reactive/oauth2/login.adoc b/docs/modules/ROOT/pages/reactive/oauth2/login.adoc index 4aee887bb36..b03e5ca1d01 100644 --- a/docs/modules/ROOT/pages/reactive/oauth2/login.adoc +++ b/docs/modules/ROOT/pages/reactive/oauth2/login.adoc @@ -1,16 +1,16 @@ [[webflux-oauth2-login]] = OAuth 2.0 Login -The OAuth 2.0 Login feature provides an application with the capability to have users log in to the application by using their existing account at an OAuth 2.0 Provider (e.g. -GitHub) or OpenID Connect 1.0 Provider (such as Google). +The OAuth 2.0 Login feature provides an application with the capability to have users log in to the application by using their existing account at an OAuth 2.0 Provider (e.g. GitHub) or OpenID Connect 1.0 Provider (such as Google). OAuth 2.0 Login implements the use cases: "Login with Google" or "Login with GitHub". NOTE: OAuth 2.0 Login is implemented by using the *Authorization Code Grant*, as specified in the https://tools.ietf.org/html/rfc6749#section-4.1[OAuth 2.0 Authorization Framework] and https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth[OpenID Connect Core 1.0]. + [[webflux-oauth2-login-sample]] -== Spring Boot 2.0 Sample +== Spring Boot 2.x Sample -Spring Boot 2.0 brings full auto-configuration capabilities for OAuth 2.0 Login. +Spring Boot 2.x brings full auto-configuration capabilities for OAuth 2.0 Login. This section shows how to configure the {gh-samples-url}/reactive/webflux/java/oauth2/login[*OAuth 2.0 Login WebFlux sample*] using _Google_ as the _Authentication Provider_ and covers the following topics: @@ -31,6 +31,7 @@ Follow the instructions on the https://developers.google.com/identity/protocols/ After completing the "Obtain OAuth 2.0 credentials" instructions, you should have a new OAuth Client with credentials consisting of a Client ID and a Client Secret. + [[webflux-oauth2-login-sample-redirect]] === Setting the redirect URI @@ -39,11 +40,12 @@ The redirect URI is the path in the application that the end-user's user-agent i In the "Set a redirect URI" sub-section, ensure that the *Authorized redirect URIs* field is set to `http://localhost:8080/login/oauth2/code/google`. TIP: The default redirect URI template is `+{baseUrl}/login/oauth2/code/{registrationId}+`. -The *_registrationId_* is a unique identifier for the xref:servlet/oauth2/client/core.adoc#oauth2Client-client-registration[ClientRegistration]. +The *_registrationId_* is a unique identifier for the xref:reactive/oauth2/client/core.adoc#oauth2Client-client-registration[ClientRegistration]. For our example, the `registrationId` is `google`. IMPORTANT: If the OAuth Client is running behind a proxy server, it is recommended to check xref:features/exploits/http.adoc#http-proxy-server[Proxy Server Configuration] to ensure the application is correctly configured. -Also, see the supported xref:servlet/oauth2/client/authorization-grants.adoc#oauth2Client-auth-code-redirect-uri[ `URI` template variables] for `redirect-uri`. +Also, see the supported xref:reactive/oauth2/client/authorization-grants.adoc#oauth2Client-auth-code-redirect-uri[ `URI` template variables] for `redirect-uri`. + [[webflux-oauth2-login-sample-config]] === Configure `application.yml` @@ -68,7 +70,7 @@ spring: .OAuth Client properties ==== <1> `spring.security.oauth2.client.registration` is the base property prefix for OAuth Client properties. -<2> Following the base property prefix is the ID for the xref:servlet/oauth2/client/index.adoc#oauth2Client-client-registration[`ClientRegistration`], such as google. +<2> Following the base property prefix is the ID for the xref:reactive/oauth2/client/core.adoc#oauth2Client-client-registration[`ClientRegistration`], such as google. ==== . Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier. @@ -77,7 +79,7 @@ spring: [[webflux-oauth2-login-sample-start]] === Boot up the application -Launch the Spring Boot 2.0 sample and go to `http://localhost:8080`. +Launch the Spring Boot 2.x sample and go to `http://localhost:8080`. You are then redirected to the default _auto-generated_ login page, which displays a link for Google. Click on the Google link, and you are then redirected to Google for authentication. @@ -88,158 +90,1224 @@ Click *Allow* to authorize the OAuth Client to access your email address and bas At this point, the OAuth Client retrieves your email address and basic profile information from the https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] and establishes an authenticated session. -[[webflux-oauth2-login-openid-provider-configuration]] -== Using OpenID Provider Configuration -For well known providers, Spring Security provides the necessary defaults for the OAuth Authorization Provider's configuration. -If you are working with your own Authorization Provider that supports https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[OpenID Provider Configuration] or https://tools.ietf.org/html/rfc8414#section-3[Authorization Server Metadata], the https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse[OpenID Provider Configuration Response]'s `issuer-uri` can be used to configure the application. +[[oauth2login-boot-property-mappings]] +== Spring Boot 2.x Property Mappings + +The following table outlines the mapping of the Spring Boot 2.x OAuth Client properties to the xref:reactive/oauth2/client/core.adoc#oauth2Client-client-registration[ClientRegistration] properties. + +|=== +|Spring Boot 2.x |ClientRegistration + +|`spring.security.oauth2.client.registration._[registrationId]_` +|`registrationId` + +|`spring.security.oauth2.client.registration._[registrationId]_.client-id` +|`clientId` + +|`spring.security.oauth2.client.registration._[registrationId]_.client-secret` +|`clientSecret` + +|`spring.security.oauth2.client.registration._[registrationId]_.client-authentication-method` +|`clientAuthenticationMethod` + +|`spring.security.oauth2.client.registration._[registrationId]_.authorization-grant-type` +|`authorizationGrantType` + +|`spring.security.oauth2.client.registration._[registrationId]_.redirect-uri` +|`redirectUri` + +|`spring.security.oauth2.client.registration._[registrationId]_.scope` +|`scopes` + +|`spring.security.oauth2.client.registration._[registrationId]_.client-name` +|`clientName` + +|`spring.security.oauth2.client.provider._[providerId]_.authorization-uri` +|`providerDetails.authorizationUri` + +|`spring.security.oauth2.client.provider._[providerId]_.token-uri` +|`providerDetails.tokenUri` -[source,yml] +|`spring.security.oauth2.client.provider._[providerId]_.jwk-set-uri` +|`providerDetails.jwkSetUri` + +|`spring.security.oauth2.client.provider._[providerId]_.issuer-uri` +|`providerDetails.issuerUri` + +|`spring.security.oauth2.client.provider._[providerId]_.user-info-uri` +|`providerDetails.userInfoEndpoint.uri` + +|`spring.security.oauth2.client.provider._[providerId]_.user-info-authentication-method` +|`providerDetails.userInfoEndpoint.authenticationMethod` + +|`spring.security.oauth2.client.provider._[providerId]_.user-name-attribute` +|`providerDetails.userInfoEndpoint.userNameAttributeName` +|=== + +[TIP] +A `ClientRegistration` can be initially configured using discovery of an OpenID Connect Provider's https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Configuration endpoint] or an Authorization Server's https://tools.ietf.org/html/rfc8414#section-3[Metadata endpoint], by specifying the `spring.security.oauth2.client.provider._[providerId]_.issuer-uri` property. + + +[[webflux-oauth2-login-common-oauth2-provider]] +== CommonOAuth2Provider + +`CommonOAuth2Provider` pre-defines a set of default client properties for a number of well known providers: Google, GitHub, Facebook, and Okta. + +For example, the `authorization-uri`, `token-uri`, and `user-info-uri` do not change often for a Provider. +Therefore, it makes sense to provide default values in order to reduce the required configuration. + +As demonstrated previously, when we <>, only the `client-id` and `client-secret` properties are required. + +The following listing shows an example: + +[source,yaml] ---- spring: security: oauth2: client: - provider: - keycloak: - issuer-uri: https://idp.example.com/auth/realms/demo registration: - keycloak: - client-id: spring-security - client-secret: 6cea952f-10d0-4d00-ac79-cc865820dc2c + google: + client-id: google-client-id + client-secret: google-client-secret +---- + +[TIP] +The auto-defaulting of client properties works seamlessly here because the `registrationId` (`google`) matches the `GOOGLE` `enum` (case-insensitive) in `CommonOAuth2Provider`. + +For cases where you may want to specify a different `registrationId`, such as `google-login`, you can still leverage auto-defaulting of client properties by configuring the `provider` property. + +The following listing shows an example: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + google-login: <1> + provider: google <2> + client-id: google-client-id + client-secret: google-client-secret +---- +<1> The `registrationId` is set to `google-login`. +<2> The `provider` property is set to `google`, which will leverage the auto-defaulting of client properties set in `CommonOAuth2Provider.GOOGLE.getBuilder()`. + + +[[webflux-oauth2-login-custom-provider-properties]] +== Configuring Custom Provider Properties + +There are some OAuth 2.0 Providers that support multi-tenancy, which results in different protocol endpoints for each tenant (or sub-domain). + +For example, an OAuth Client registered with Okta is assigned to a specific sub-domain and have their own protocol endpoints. + +For these cases, Spring Boot 2.x provides the following base property for configuring custom provider properties: `spring.security.oauth2.client.provider._[providerId]_`. + +The following listing shows an example: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + provider: + okta: <1> + authorization-uri: https://your-subdomain.oktapreview.com/oauth2/v1/authorize + token-uri: https://your-subdomain.oktapreview.com/oauth2/v1/token + user-info-uri: https://your-subdomain.oktapreview.com/oauth2/v1/userinfo + user-name-attribute: sub + jwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys +---- + +<1> The base property (`spring.security.oauth2.client.provider.okta`) allows for custom configuration of protocol endpoint locations. + + +[[webflux-oauth2-login-override-boot-autoconfig]] +== Overriding Spring Boot 2.x Auto-configuration + +The Spring Boot 2.x auto-configuration class for OAuth Client support is `ReactiveOAuth2ClientAutoConfiguration`. + +It performs the following tasks: + +* Registers a `ReactiveClientRegistrationRepository` `@Bean` composed of `ClientRegistration`(s) from the configured OAuth Client properties. +* Registers a `SecurityWebFilterChain` `@Bean` and enables OAuth 2.0 Login through `serverHttpSecurity.oauth2Login()`. + +If you need to override the auto-configuration based on your specific requirements, you may do so in the following ways: + +* <> +* <> +* <> + + +[[webflux-oauth2-login-register-reactiveclientregistrationrepository-bean]] +=== Register a ReactiveClientRegistrationRepository @Bean + +The following example shows how to register a `ReactiveClientRegistrationRepository` `@Bean`: + +==== +.Java +[source,java,role="primary",attrs="-attributes"] +---- +@Configuration +public class OAuth2LoginConfig { + + @Bean + public ReactiveClientRegistrationRepository clientRegistrationRepository() { + return new InMemoryReactiveClientRegistrationRepository(this.googleClientRegistration()); + } + + private ClientRegistration googleClientRegistration() { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary",attrs="-attributes"] +---- +@Configuration +class OAuth2LoginConfig { + + @Bean + fun clientRegistrationRepository(): ReactiveClientRegistrationRepository { + return InMemoryReactiveClientRegistrationRepository(googleClientRegistration()) + } + + private fun googleClientRegistration(): ClientRegistration { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build() + } +} +---- +==== + + +[[webflux-oauth2-login-register-securitywebfilterchain-bean]] +=== Register a SecurityWebFilterChain @Bean + +The following example shows how to register a `SecurityWebFilterChain` `@Bean` with `@EnableWebFluxSecurity` and enable OAuth 2.0 login through `serverHttpSecurity.oauth2Login()`: + +.OAuth2 Login Configuration +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(authorize -> authorize + .anyExchange().authenticated() + ) + .oauth2Login(withDefaults()); + + return http.build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2Login { } + } + + return http.build() + } +} +---- +==== + + +[[webflux-oauth2-login-completely-override-autoconfiguration]] +=== Completely Override the Auto-configuration + +The following example shows how to completely override the auto-configuration by registering a `ReactiveClientRegistrationRepository` `@Bean` and a `SecurityWebFilterChain` `@Bean`. + +.Overriding the auto-configuration +==== +.Java +[source,java,role="primary",attrs="-attributes"] ---- +@EnableWebFluxSecurity +public class OAuth2LoginConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(authorize -> authorize + .anyExchange().authenticated() + ) + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ClientRegistrationRepository clientRegistrationRepository() { + return new InMemoryClientRegistrationRepository(this.googleClientRegistration()); + } + + private ClientRegistration googleClientRegistration() { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary",attrs="-attributes"] +---- +@EnableWebFluxSecurity +class OAuth2LoginConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2Login { } + } + + return http.build() + } + + @Bean + fun clientRegistrationRepository(): ReactiveClientRegistrationRepository { + return InMemoryReactiveClientRegistrationRepository(googleClientRegistration()) + } + + private fun googleClientRegistration(): ClientRegistration { + return ClientRegistration.withRegistrationId("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .redirectUri("{baseUrl}/login/oauth2/code/{registrationId}") + .scope("openid", "profile", "email", "address", "phone") + .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") + .tokenUri("https://www.googleapis.com/oauth2/v4/token") + .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") + .userNameAttributeName(IdTokenClaimNames.SUB) + .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") + .clientName("Google") + .build() + } +} +---- +==== + + +[[webflux-oauth2-login-javaconfig-wo-boot]] +== Java Configuration without Spring Boot 2.x -The `issuer-uri` instructs Spring Security to query in series the endpoints `https://idp.example.com/auth/realms/demo/.well-known/openid-configuration`, `https://idp.example.com/.well-known/openid-configuration/auth/realms/demo`, or `https://idp.example.com/.well-known/oauth-authorization-server/auth/realms/demo` to discover the configuration. +If you are not able to use Spring Boot 2.x and would like to configure one of the pre-defined providers in `CommonOAuth2Provider` (for example, Google), apply the following configuration: + +.OAuth2 Login Configuration +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(authorize -> authorize + .anyExchange().authenticated() + ) + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveClientRegistrationRepository clientRegistrationRepository() { + return new InMemoryReactiveClientRegistrationRepository(this.googleClientRegistration()); + } + + @Bean + public ReactiveOAuth2AuthorizedClientService authorizedClientService( + ReactiveClientRegistrationRepository clientRegistrationRepository) { + return new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository); + } + + @Bean + public ServerOAuth2AuthorizedClientRepository authorizedClientRepository( + ReactiveOAuth2AuthorizedClientService authorizedClientService) { + return new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService); + } + + private ClientRegistration googleClientRegistration() { + return CommonOAuth2Provider.GOOGLE.getBuilder("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2Login { } + } + + return http.build() + } + + @Bean + fun clientRegistrationRepository(): ReactiveClientRegistrationRepository { + return InMemoryReactiveClientRegistrationRepository(googleClientRegistration()) + } + + @Bean + fun authorizedClientService( + clientRegistrationRepository: ReactiveClientRegistrationRepository + ): ReactiveOAuth2AuthorizedClientService { + return InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository) + } + + @Bean + fun authorizedClientRepository( + authorizedClientService: ReactiveOAuth2AuthorizedClientService + ): ServerOAuth2AuthorizedClientRepository { + return AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(authorizedClientService) + } + + private fun googleClientRegistration(): ClientRegistration { + return CommonOAuth2Provider.GOOGLE.getBuilder("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .build() + } +} +---- +==== + + +[[webflux-oauth2-login-advanced]] +== Advanced Configuration + +The OAuth 2.0 Authorization Framework defines the https://tools.ietf.org/html/rfc6749#section-3[Protocol Endpoints] as follows: + +The authorization process utilizes two authorization server endpoints (HTTP resources): + +* Authorization Endpoint: Used by the client to obtain authorization from the resource owner via user-agent redirection. +* Token Endpoint: Used by the client to exchange an authorization grant for an access token, typically with client authentication. + +As well as one client endpoint: + +* Redirection Endpoint: Used by the authorization server to return responses containing authorization credentials to the client via the resource owner user-agent. + +The OpenID Connect Core 1.0 specification defines the https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] as follows: + +The UserInfo Endpoint is an OAuth 2.0 Protected Resource that returns claims about the authenticated end-user. +To obtain the requested claims about the end-user, the client makes a request to the UserInfo Endpoint by using an access token obtained through OpenID Connect Authentication. +These claims are normally represented by a JSON object that contains a collection of name-value pairs for the claims. + +`ServerHttpSecurity.oauth2Login()` provides a number of configuration options for customizing OAuth 2.0 Login. + +The following code shows the complete configuration options available for the `oauth2Login()` DSL: + +.OAuth2 Login Configuration Options +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + http + .oauth2Login(oauth2 -> oauth2 + .authenticationConverter(this.authenticationConverter()) + .authenticationMatcher(this.authenticationMatcher()) + .authenticationManager(this.authenticationManager()) + .authenticationSuccessHandler(this.authenticationSuccessHandler()) + .authenticationFailureHandler(this.authenticationFailureHandler()) + .clientRegistrationRepository(this.clientRegistrationRepository()) + .authorizedClientRepository(this.authorizedClientRepository()) + .authorizedClientService(this.authorizedClientService()) + .authorizationRequestResolver(this.authorizationRequestResolver()) + .authorizationRequestRepository(this.authorizationRequestRepository()) + .securityContextRepository(this.securityContextRepository()) + ); + + return http.build(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + oauth2Login { + authenticationConverter = authenticationConverter() + authenticationMatcher = authenticationMatcher() + authenticationManager = authenticationManager() + authenticationSuccessHandler = authenticationSuccessHandler() + authenticationFailureHandler = authenticationFailureHandler() + clientRegistrationRepository = clientRegistrationRepository() + authorizedClientRepository = authorizedClientRepository() + authorizedClientService = authorizedClientService() + authorizationRequestResolver = authorizationRequestResolver() + authorizationRequestRepository = authorizationRequestRepository() + securityContextRepository = securityContextRepository() + } + } + + return http.build() + } +} +---- +==== + +The following sections go into more detail on each of the configuration options available: + +* <> +* <> +* <> +* <> +* <> + + +[[webflux-oauth2-login-advanced-login-page]] +=== OAuth 2.0 Login Page + +By default, the OAuth 2.0 Login Page is auto-generated by the `LoginPageGeneratingWebFilter`. +The default login page shows each configured OAuth Client with its `ClientRegistration.clientName` as a link, which is capable of initiating the Authorization Request (or OAuth 2.0 Login). [NOTE] -Spring Security will query the endpoints one at a time, stopping at the first that gives a 200 response. +In order for `LoginPageGeneratingWebFilter` to show links for configured OAuth Clients, the registered `ReactiveClientRegistrationRepository` needs to also implement `Iterable`. +See `InMemoryReactiveClientRegistrationRepository` for reference. + +The link's destination for each OAuth Client defaults to the following: + +`+"/oauth2/authorization/{registrationId}"+` -The `client-id` and `client-secret` are linked to the provider because `keycloak` is used for both the provider and the registration. +The following line shows an example: +[source,html] +---- +Google +---- -[[webflux-oauth2-login-explicit]] -== Explicit OAuth2 Login Configuration +To override the default login page, configure the `exceptionHandling().authenticationEntryPoint()` and (optionally) `oauth2Login().authorizationRequestResolver()`. -A minimal OAuth2 Login configuration is shown below: +The following listing shows an example: -.Minimal OAuth2 Login +.OAuth2 Login Page Configuration ==== .Java [source,java,role="primary"] ---- -@Bean -ReactiveClientRegistrationRepository clientRegistrations() { - ClientRegistration clientRegistration = ClientRegistrations - .fromIssuerLocation("https://idp.example.com/auth/realms/demo") - .clientId("spring-security") - .clientSecret("6cea952f-10d0-4d00-ac79-cc865820dc2c") - .build(); - return new InMemoryReactiveClientRegistrationRepository(clientRegistration); +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .exceptionHandling(exceptions -> exceptions + .authenticationEntryPoint(new RedirectServerAuthenticationEntryPoint("/login/oauth2")) + ) + .oauth2Login(oauth2 -> oauth2 + .authorizationRequestResolver(this.authorizationRequestResolver()) + ); + + return http.build(); + } + + private ServerOAuth2AuthorizationRequestResolver authorizationRequestResolver() { + ServerWebExchangeMatcher authorizationRequestMatcher = + new PathPatternParserServerWebExchangeMatcher( + "/login/oauth2/authorization/{registrationId}"); + + return new DefaultServerOAuth2AuthorizationRequestResolver( + this.clientRegistrationRepository(), authorizationRequestMatcher); + } + + ... } +---- -@Bean -SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http - // ... - .oauth2Login(withDefaults()); - return http.build(); +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + exceptionHandling { + authenticationEntryPoint = RedirectServerAuthenticationEntryPoint("/login/oauth2") + } + oauth2Login { + authorizationRequestResolver = authorizationRequestResolver() + } + } + + return http.build() + } + + private fun authorizationRequestResolver(): ServerOAuth2AuthorizationRequestResolver { + val authorizationRequestMatcher: ServerWebExchangeMatcher = PathPatternParserServerWebExchangeMatcher( + "/login/oauth2/authorization/{registrationId}" + ) + + return DefaultServerOAuth2AuthorizationRequestResolver( + clientRegistrationRepository(), authorizationRequestMatcher + ) + } + + ... +} +---- +==== + +[IMPORTANT] +You need to provide a `@Controller` with a `@RequestMapping("/login/oauth2")` that is capable of rendering the custom login page. + +[TIP] +==== +As noted earlier, configuring `oauth2Login().authorizationRequestResolver()` is optional. +However, if you choose to customize it, ensure the link to each OAuth Client matches the pattern provided through the `ServerWebExchangeMatcher`. + +The following line shows an example: + +[source,html] +---- +Google +---- +==== + + +[[webflux-oauth2-login-advanced-redirection-endpoint]] +=== Redirection Endpoint + +The Redirection Endpoint is used by the Authorization Server for returning the Authorization Response (which contains the authorization credentials) to the client via the Resource Owner user-agent. + +[TIP] +OAuth 2.0 Login leverages the Authorization Code Grant. +Therefore, the authorization credential is the authorization code. + +The default Authorization Response redirection endpoint is `/login/oauth2/code/{registrationId}`. + +If you would like to customize the Authorization Response redirection endpoint, configure it as shown in the following example: + +.Redirection Endpoint Configuration +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .oauth2Login(oauth2 -> oauth2 + .authenticationMatcher(new PathPatternParserServerWebExchangeMatcher("/login/oauth2/callback/{registrationId}")) + ); + + return http.build(); + } } ---- .Kotlin [source,kotlin,role="secondary"] ---- -@Bean -fun clientRegistrations(): ReactiveClientRegistrationRepository { - val clientRegistration: ClientRegistration = ClientRegistrations - .fromIssuerLocation("https://idp.example.com/auth/realms/demo") - .clientId("spring-security") - .clientSecret("6cea952f-10d0-4d00-ac79-cc865820dc2c") - .build() - return InMemoryReactiveClientRegistrationRepository(clientRegistration) +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + oauth2Login { + authenticationMatcher = PathPatternParserServerWebExchangeMatcher("/login/oauth2/callback/{registrationId}") + } + } + + return http.build() + } } +---- +==== -@Bean -fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { - return http { - oauth2Login { } +[IMPORTANT] +==== +You also need to ensure the `ClientRegistration.redirectUri` matches the custom Authorization Response redirection endpoint. + +The following listing shows an example: + +.Java +[source,java,role="primary",attrs="-attributes"] +---- +return CommonOAuth2Provider.GOOGLE.getBuilder("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .redirectUri("{baseUrl}/login/oauth2/callback/{registrationId}") + .build(); +---- + +.Kotlin +[source,kotlin,role="secondary",attrs="-attributes"] +---- +return CommonOAuth2Provider.GOOGLE.getBuilder("google") + .clientId("google-client-id") + .clientSecret("google-client-secret") + .redirectUri("{baseUrl}/login/oauth2/callback/{registrationId}") + .build() +---- +==== + + +[[webflux-oauth2-login-advanced-userinfo-endpoint]] +=== UserInfo Endpoint + +The UserInfo Endpoint includes a number of configuration options, as described in the following sub-sections: + +* <> +* <> +* <> + + +[[webflux-oauth2-login-advanced-map-authorities]] +==== Mapping User Authorities + +After the user successfully authenticates with the OAuth 2.0 Provider, the `OAuth2User.getAuthorities()` (or `OidcUser.getAuthorities()`) may be mapped to a new set of `GrantedAuthority` instances, which will be supplied to `OAuth2AuthenticationToken` when completing the authentication. + +[TIP] +`OAuth2AuthenticationToken.getAuthorities()` is used for authorizing requests, such as in `hasRole('USER')` or `hasRole('ADMIN')`. + +There are a couple of options to choose from when mapping user authorities: + +* <> +* <> + + +[[webflux-oauth2-login-advanced-map-authorities-grantedauthoritiesmapper]] +===== Using a GrantedAuthoritiesMapper + +Register a `GrantedAuthoritiesMapper` `@Bean` to have it automatically applied to the configuration, as shown in the following example: + +.Granted Authorities Mapper Configuration +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + ... + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public GrantedAuthoritiesMapper userAuthoritiesMapper() { + return (authorities) -> { + Set mappedAuthorities = new HashSet<>(); + + authorities.forEach(authority -> { + if (OidcUserAuthority.class.isInstance(authority)) { + OidcUserAuthority oidcUserAuthority = (OidcUserAuthority)authority; + + OidcIdToken idToken = oidcUserAuthority.getIdToken(); + OidcUserInfo userInfo = oidcUserAuthority.getUserInfo(); + + // Map the claims found in idToken and/or userInfo + // to one or more GrantedAuthority's and add it to mappedAuthorities + + } else if (OAuth2UserAuthority.class.isInstance(authority)) { + OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority)authority; + + Map userAttributes = oauth2UserAuthority.getAttributes(); + + // Map the attributes found in userAttributes + // to one or more GrantedAuthority's and add it to mappedAuthorities + + } + }); + + return mappedAuthorities; + }; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + oauth2Login { } + } + + return http.build() + } + + @Bean + fun userAuthoritiesMapper(): GrantedAuthoritiesMapper = GrantedAuthoritiesMapper { authorities: Collection -> + val mappedAuthorities = emptySet() + + authorities.forEach { authority -> + if (authority is OidcUserAuthority) { + val idToken = authority.idToken + val userInfo = authority.userInfo + // Map the claims found in idToken and/or userInfo + // to one or more GrantedAuthority's and add it to mappedAuthorities + } else if (authority is OAuth2UserAuthority) { + val userAttributes = authority.attributes + // Map the attributes found in userAttributes + // to one or more GrantedAuthority's and add it to mappedAuthorities + } + } + + mappedAuthorities } } ---- ==== -Additional configuration options can be seen below: +[[webflux-oauth2-login-advanced-map-authorities-reactiveoauth2userservice]] +===== Delegation-based strategy with ReactiveOAuth2UserService + +This strategy is advanced compared to using a `GrantedAuthoritiesMapper`, however, it's also more flexible as it gives you access to the `OAuth2UserRequest` and `OAuth2User` (when using an OAuth 2.0 UserService) or `OidcUserRequest` and `OidcUser` (when using an OpenID Connect 1.0 UserService). + +The `OAuth2UserRequest` (and `OidcUserRequest`) provides you access to the associated `OAuth2AccessToken`, which is very useful in the cases where the _delegator_ needs to fetch authority information from a protected resource before it can map the custom authorities for the user. -.Advanced OAuth2 Login +The following example shows how to implement and configure a delegation-based strategy using an OpenID Connect 1.0 UserService: + +.ReactiveOAuth2UserService Configuration ==== .Java [source,java,role="primary"] ---- -@Bean -SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http - // ... - .oauth2Login(oauth2 -> oauth2 - .authenticationConverter(converter) - .authenticationManager(manager) - .authorizedClientRepository(authorizedClients) - .clientRegistrationRepository(clientRegistrations) - ); - return http.build(); +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + ... + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveOAuth2UserService oidcUserService() { + final OidcReactiveOAuth2UserService delegate = new OidcReactiveOAuth2UserService(); + + return (userRequest) -> { + // Delegate to the default implementation for loading a user + return delegate.loadUser(userRequest) + .flatMap((oidcUser) -> { + OAuth2AccessToken accessToken = userRequest.getAccessToken(); + Set mappedAuthorities = new HashSet<>(); + + // TODO + // 1) Fetch the authority information from the protected resource using accessToken + // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities + + // 3) Create a copy of oidcUser but use the mappedAuthorities instead + oidcUser = new DefaultOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo()); + + return Mono.just(oidcUser); + }); + }; + } } ---- .Kotlin [source,kotlin,role="secondary"] ---- -@Bean -fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { - return http { - oauth2Login { - authenticationConverter = converter - authenticationManager = manager - authorizedClientRepository = authorizedClients - clientRegistrationRepository = clientRegistration +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + oauth2Login { } + } + + return http.build() + } + + @Bean + fun oidcUserService(): ReactiveOAuth2UserService { + val delegate = OidcReactiveOAuth2UserService() + + return ReactiveOAuth2UserService { userRequest -> + // Delegate to the default implementation for loading a user + delegate.loadUser(userRequest) + .flatMap { oidcUser -> + val accessToken = userRequest.accessToken + val mappedAuthorities = mutableSetOf() + + // TODO + // 1) Fetch the authority information from the protected resource using accessToken + // 2) Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities + // 3) Create a copy of oidcUser but use the mappedAuthorities instead + val mappedOidcUser = DefaultOidcUser(mappedAuthorities, oidcUser.idToken, oidcUser.userInfo) + + Mono.just(mappedOidcUser) + } } } } ---- ==== -You may register a `GrantedAuthoritiesMapper` `@Bean` to have it automatically applied to the default configuration, as shown in the following example: -.GrantedAuthoritiesMapper Bean +[[webflux-oauth2-login-advanced-oauth2-user-service]] +==== OAuth 2.0 UserService + +`DefaultReactiveOAuth2UserService` is an implementation of a `ReactiveOAuth2UserService` that supports standard OAuth 2.0 Provider's. + +[NOTE] +`ReactiveOAuth2UserService` obtains the user attributes of the end-user (the resource owner) from the UserInfo Endpoint (by using the access token granted to the client during the authorization flow) and returns an `AuthenticatedPrincipal` in the form of an `OAuth2User`. + +`DefaultReactiveOAuth2UserService` uses a `WebClient` when requesting the user attributes at the UserInfo Endpoint. + +If you need to customize the pre-processing of the UserInfo Request and/or the post-handling of the UserInfo Response, you will need to provide `DefaultReactiveOAuth2UserService.setWebClient()` with a custom configured `WebClient`. + +Whether you customize `DefaultReactiveOAuth2UserService` or provide your own implementation of `ReactiveOAuth2UserService`, you'll need to configure it as shown in the following example: + ==== .Java [source,java,role="primary"] ---- -@Bean -public GrantedAuthoritiesMapper userAuthoritiesMapper() { - ... +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + ... + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveOAuth2UserService oauth2UserService() { + ... + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + oauth2Login { } + } + + return http.build() + } + + @Bean + fun oauth2UserService(): ReactiveOAuth2UserService { + // ... + } } +---- +==== -@Bean -SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http - // ... - .oauth2Login(withDefaults()); - return http.build(); + +[[webflux-oauth2-login-advanced-oidc-user-service]] +==== OpenID Connect 1.0 UserService + +`OidcReactiveOAuth2UserService` is an implementation of a `ReactiveOAuth2UserService` that supports OpenID Connect 1.0 Provider's. + +The `OidcReactiveOAuth2UserService` leverages the `DefaultReactiveOAuth2UserService` when requesting the user attributes at the UserInfo Endpoint. + +If you need to customize the pre-processing of the UserInfo Request and/or the post-handling of the UserInfo Response, you will need to provide `OidcReactiveOAuth2UserService.setOauth2UserService()` with a custom configured `ReactiveOAuth2UserService`. + +Whether you customize `OidcReactiveOAuth2UserService` or provide your own implementation of `ReactiveOAuth2UserService` for OpenID Connect 1.0 Provider's, you'll need to configure it as shown in the following example: + +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + ... + .oauth2Login(withDefaults()); + + return http.build(); + } + + @Bean + public ReactiveOAuth2UserService oidcUserService() { + ... + } } ---- .Kotlin [source,kotlin,role="secondary"] ---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + oauth2Login { } + } + + return http.build() + } + + @Bean + fun oidcUserService(): ReactiveOAuth2UserService { + // ... + } +} +---- +==== + + +[[webflux-oauth2-login-advanced-idtoken-verify]] +=== ID Token Signature Verification + +OpenID Connect 1.0 Authentication introduces the https://openid.net/specs/openid-connect-core-1_0.html#IDToken[ID Token], which is a security token that contains Claims about the Authentication of an End-User by an Authorization Server when used by a Client. + +The ID Token is represented as a https://tools.ietf.org/html/rfc7519[JSON Web Token] (JWT) and MUST be signed using https://tools.ietf.org/html/rfc7515[JSON Web Signature] (JWS). + +The `ReactiveOidcIdTokenDecoderFactory` provides a `ReactiveJwtDecoder` used for `OidcIdToken` signature verification. The default algorithm is `RS256` but may be different when assigned during client registration. +For these cases, a resolver may be configured to return the expected JWS algorithm assigned for a specific client. + +The JWS algorithm resolver is a `Function` that accepts a `ClientRegistration` and returns the expected `JwsAlgorithm` for the client, eg. `SignatureAlgorithm.RS256` or `MacAlgorithm.HS256` + +The following code shows how to configure the `OidcIdTokenDecoderFactory` `@Bean` to default to `MacAlgorithm.HS256` for all `ClientRegistration`: + +==== +.Java +[source,java,role="primary"] +---- @Bean -fun userAuthoritiesMapper(): GrantedAuthoritiesMapper { - // ... +public ReactiveJwtDecoderFactory idTokenDecoderFactory() { + ReactiveOidcIdTokenDecoderFactory idTokenDecoderFactory = new ReactiveOidcIdTokenDecoderFactory(); + idTokenDecoderFactory.setJwsAlgorithmResolver(clientRegistration -> MacAlgorithm.HS256); + return idTokenDecoderFactory; } +---- +.Kotlin +[source,kotlin,role="secondary"] +---- @Bean -fun webFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { - return http { - oauth2Login { } +fun idTokenDecoderFactory(): ReactiveJwtDecoderFactory { + val idTokenDecoderFactory = ReactiveOidcIdTokenDecoderFactory() + idTokenDecoderFactory.setJwsAlgorithmResolver { MacAlgorithm.HS256 } + return idTokenDecoderFactory +} +---- +==== + +[NOTE] +For MAC based algorithms such as `HS256`, `HS384` or `HS512`, the `client-secret` corresponding to the `client-id` is used as the symmetric key for signature verification. + +[TIP] +If more than one `ClientRegistration` is configured for OpenID Connect 1.0 Authentication, the JWS algorithm resolver may evaluate the provided `ClientRegistration` to determine which algorithm to return. + + +[[webflux-oauth2-login-advanced-oidc-logout]] +=== OpenID Connect 1.0 Logout + +OpenID Connect Session Management 1.0 allows the ability to log out the End-User at the Provider using the Client. +One of the strategies available is https://openid.net/specs/openid-connect-session-1_0.html#RPLogout[RP-Initiated Logout]. + +If the OpenID Provider supports both Session Management and https://openid.net/specs/openid-connect-discovery-1_0.html[Discovery], the client may obtain the `end_session_endpoint` `URL` from the OpenID Provider's https://openid.net/specs/openid-connect-session-1_0.html#OPMetadata[Discovery Metadata]. +This can be achieved by configuring the `ClientRegistration` with the `issuer-uri`, as in the following example: + +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: + okta: + client-id: okta-client-id + client-secret: okta-client-secret + ... + provider: + okta: + issuer-uri: https://dev-1234.oktapreview.com +---- + +...and the `OidcClientInitiatedServerLogoutSuccessHandler`, which implements RP-Initiated Logout, may be configured as follows: + +==== +.Java +[source,java,role="primary"] +---- +@EnableWebFluxSecurity +public class OAuth2LoginSecurityConfig { + + @Autowired + private ReactiveClientRegistrationRepository clientRegistrationRepository; + + @Bean + public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { + http + .authorizeExchange(authorize -> authorize + .anyExchange().authenticated() + ) + .oauth2Login(withDefaults()) + .logout(logout -> logout + .logoutSuccessHandler(oidcLogoutSuccessHandler()) + ); + + return http.build(); + } + + private ServerLogoutSuccessHandler oidcLogoutSuccessHandler() { + OidcClientInitiatedServerLogoutSuccessHandler oidcLogoutSuccessHandler = + new OidcClientInitiatedServerLogoutSuccessHandler(this.clientRegistrationRepository); + + // Sets the location that the End-User's User Agent will be redirected to + // after the logout has been performed at the Provider + oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}"); + + return oidcLogoutSuccessHandler; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableWebFluxSecurity +class OAuth2LoginSecurityConfig { + + @Autowired + private lateinit var clientRegistrationRepository: ReactiveClientRegistrationRepository + + @Bean + fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { + http { + authorizeExchange { + authorize(anyExchange, authenticated) + } + oauth2Login { } + logout { + logoutSuccessHandler = oidcLogoutSuccessHandler() + } + } + + return http.build() + } + + private fun oidcLogoutSuccessHandler(): ServerLogoutSuccessHandler { + val oidcLogoutSuccessHandler = OidcClientInitiatedServerLogoutSuccessHandler(clientRegistrationRepository) + + // Sets the location that the End-User's User Agent will be redirected to + // after the logout has been performed at the Provider + oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}") + return oidcLogoutSuccessHandler } } ---- ==== + +NOTE: `OidcClientInitiatedServerLogoutSuccessHandler` supports the `{baseUrl}` placeholder. +If used, the application's base URL, like `https://app.example.org`, will replace it at request time.