diff --git a/samples/boot/oauth2login-webflux/README.adoc b/samples/boot/oauth2login-webflux/README.adoc new file mode 100644 index 0000000000..b963c54240 --- /dev/null +++ b/samples/boot/oauth2login-webflux/README.adoc @@ -0,0 +1,312 @@ +NOTE: Spring Security Reactive OAuth only supports authentication using a user info endpoint. +Support for JWT validation will be added in https://github.com/spring-projects/spring-security/issues/5330[gh-5330]. + += OAuth 2.0 Login Sample + +This guide provides instructions on setting up the sample application with OAuth 2.0 Login using an OAuth 2.0 Provider or OpenID Connect 1.0 Provider. +The sample application uses Spring Boot 2.0.0.M6 and the `spring-security-oauth2-client` module which is new in Spring Security 5.0. + +The following sections provide detailed steps for setting up OAuth 2.0 Login for these Providers: + +* <> +* <> +* <> +* <> + +[[google-login]] +== Login with Google + +This section shows how to configure the sample application using Google as the Authentication Provider and covers the following topics: + +* <> +* <> +* <> +* <> + +[[google-initial-setup]] +=== Initial setup + +To use Google's OAuth 2.0 authentication system for login, you must set up a project in the Google API Console to obtain OAuth 2.0 credentials. + +NOTE: https://developers.google.com/identity/protocols/OpenIDConnect[Google's OAuth 2.0 implementation] for authentication conforms to the + http://openid.net/connect/[OpenID Connect 1.0] specification and is http://openid.net/certification/[OpenID Certified]. + +Follow the instructions on the https://developers.google.com/identity/protocols/OpenIDConnect[OpenID Connect] page, starting in the section, "Setting up OAuth 2.0". + +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. + +[[google-redirect-uri]] +=== Setting the redirect URI + +The redirect URI is the path in the application that the end-user's user-agent is redirected back to after they have authenticated with Google +and have granted access to the OAuth Client _(created in the previous step)_ on the Consent page. + +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 `ClientRegistration`. + +[[google-application-config]] +=== Configure application.yml + +Now that you have a new OAuth Client with Google, you need to configure the application to use the OAuth Client for the _authentication flow_. To do so: + +. Go to `application.yml` and set the following configuration: ++ +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: <1> + google: <2> + client-id: google-client-id + client-secret: google-client-secret +---- ++ +.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 `ClientRegistration`, such as google. +==== + +. Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier. + +[[google-boot-application]] +=== Boot up the application + +Launch the Spring Boot 2.0 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. + +After authenticating with your Google account credentials, the next page presented to you is the Consent screen. +The Consent screen asks you to either allow or deny access to the OAuth Client you created earlier. +Click *Allow* to authorize the OAuth Client to access your email address and basic profile information. + +At this point, the OAuth Client retrieves your email address and basic profile information +from the http://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] and establishes an authenticated session. + +[[github-login]] +== Login with GitHub + +This section shows how to configure the sample application using GitHub as the Authentication Provider and covers the following topics: + +* <> +* <> +* <> + +[[github-register-application]] +=== Register OAuth application + +To use GitHub's OAuth 2.0 authentication system for login, you must https://github.com/settings/applications/new[Register a new OAuth application]. + +When registering the OAuth application, ensure the *Authorization callback URL* is set to `http://localhost:8080/login/oauth2/code/github`. + +The Authorization callback URL (redirect URI) is the path in the application that the end-user's user-agent is redirected back to after they have authenticated with GitHub +and have granted access to the OAuth application on the _Authorize application_ page. + +TIP: The default redirect URI template is `{baseUrl}/login/oauth2/code/{registrationId}`. + The *_registrationId_* is a unique identifier for the `ClientRegistration`. + +[[github-application-config]] +=== Configure application.yml + +Now that you have a new OAuth application with GitHub, you need to configure the application to use the OAuth application for the _authentication flow_. To do so: + +. Go to `application.yml` and set the following configuration: ++ +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: <1> + github: <2> + client-id: github-client-id + client-secret: github-client-secret +---- ++ +.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 `ClientRegistration`, such as github. +==== + +. Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier. + +[[github-boot-application]] +=== Boot up the application + +Launch the Spring Boot 2.0 sample and go to `http://localhost:8080`. +You are then redirected to the default _auto-generated_ login page, which displays a link for GitHub. + +Click on the GitHub link, and you are then redirected to GitHub for authentication. + +After authenticating with your GitHub credentials, the next page presented to you is "Authorize application". +This page will ask you to *Authorize* the application you created in the previous step. +Click _Authorize application_ to allow the OAuth application to access your personal user data information. + +At this point, the OAuth Client retrieves your personal user information +from the UserInfo Endpoint and establishes an authenticated session. + +[TIP] +For detailed information returned from the UserInfo Endpoint, see the API documentation +for https://developer.github.com/v3/users/#get-the-authenticated-user["Get the authenticated user"]. + +[[facebook-login]] +== Login with Facebook + +This section shows how to configure the sample application using Facebook as the Authentication Provider and covers the following topics: + +* <> +* <> +* <> + +[[facebook-register-application]] +=== Add a New App + +To use Facebook's OAuth 2.0 authentication system for login, you must first https://developers.facebook.com/apps[Add a New App]. + +Select "Create a New App" and then the "Create a New App ID" page is presented. Enter the Display Name, Contact Email, Category and then click "Create App ID". + +NOTE: The selection for the _Category_ field is not relevant but it's a required field - select "Local". + +The next page presented is "Product Setup". Click the "Get Started" button for the *Facebook Login* product. +In the left sidebar, under _Products -> Facebook Login_, select _Settings_. + +For the field *Valid OAuth redirect URIs*, enter `http://localhost:8080/login/oauth2/code/facebook` then click _Save Changes_. + +The OAuth redirect URI is the path in the application that the end-user's user-agent is redirected back to after they have authenticated with Facebook +and have granted access to the application on the _Authorize application_ page. + +TIP: The default redirect URI template is `{baseUrl}/login/oauth2/code/{registrationId}`. + The *_registrationId_* is a unique identifier for the `ClientRegistration`. + +[[facebook-application-config]] +=== Configure application.yml + +Now that you have created a new application with Facebook, you need to configure the sample application to use the application for the _authentication flow_. To do so: + +. Go to `application.yml` and set the following configuration: ++ +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: <1> + facebook: <2> + client-id: facebook-client-id + client-secret: facebook-client-secret +---- ++ +.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 `ClientRegistration`, such as facebook. +==== + +. Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier. + +[[facebook-boot-application]] +=== Boot up the application + +Launch the Spring Boot 2.0 sample and go to `http://localhost:8080`. +You are then redirected to the default _auto-generated_ login page, which displays a link for Facebook. + +Click on the Facebook link, and you are then redirected to Facebook for authentication. + +After authenticating with your Facebook credentials, the next page presented to you is "Authorize application". +This page will ask you to *Authorize* the application you created in the previous step. +Click _Authorize application_ to allow the OAuth application to access your _public profile_ and _email address_ information. + +At this point, the OAuth Client retrieves your personal user information +from the UserInfo Endpoint and establishes an authenticated session. + +[[okta-login]] +== Login with Okta + +This section shows how to configure the sample application using Okta as the Authentication Provider and covers the following topics: + +* <> +* <> +* <> +* <> + +[[okta-register-application]] +=== Add Application + +To use Okta's OAuth 2.0 authentication system for login, you must first https://www.okta.com/developer/signup[create a developer account]. + +Sign in to your account sub-domain and navigate to _Applications -> Applications_ and then select the "Add Application" button. +From the "Add Application" page, select the "Create New App" button and enter the following: + +* *Platform:* Web +* *Sign on method:* OpenID Connect + +Select the _Create_ button. +On the "General Settings" page, enter the Application Name (for example, "Spring Security Okta Login") and then select the _Next_ button. +On the "Configure OpenID Connect" page, enter `http://localhost:8080/login/oauth2/code/okta` for the field *Redirect URIs* and then select _Finish_. + +The redirect URI is the path in the application that the end-user's user-agent is redirected back to after they have authenticated with Okta +and have granted access to the application on the _Authorize application_ page. + +TIP: The default redirect URI template is `{baseUrl}/login/oauth2/code/{registrationId}`. + The *_registrationId_* is a unique identifier for the `ClientRegistration`. + +[[okta-assign-application-people]] +=== Assign Application to People + +From the "General" tab of the application, select the "Assignments" tab and then select the _Assign_ button. +Select _Assign to People_ and assign your account to the application. Then select the _Save and Go Back_ button. + +[[okta-application-config]] +=== Configure application.yml + +Now that you have created a new application with Okta, you need to configure the sample application to use the application for the _authentication flow_. To do so: + +. Go to `application.yml` and set the following configuration: ++ +[source,yaml] +---- +spring: + security: + oauth2: + client: + registration: <1> + okta: <2> + client-id: okta-client-id + client-secret: okta-client-secret + provider: <3> + okta: + 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 +---- ++ +.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 `ClientRegistration`, such as okta. +<3> `spring.security.oauth2.client.provider` is the base property prefix for OAuth Provider properties. +==== + +. Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier. +As well, replace `https://your-subdomain.oktapreview.com` in `authorization-uri`, `token-uri`, `user-info-uri` and `jwk-set-uri` with the sub-domain assigned to your account during the registration process. + +[[okta-boot-application]] +=== Boot up the application + +Launch the Spring Boot 2.0 sample and go to `http://localhost:8080`. +You are then redirected to the default _auto-generated_ login page, which displays a link for Okta. + +Click on the Okta link, and you are then redirected to Okta for authentication. + +After authenticating with your Okta account credentials, the OAuth Client retrieves your email address and basic profile information +from the http://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] and establishes an authenticated session. diff --git a/samples/boot/oauth2login-webflux/spring-security-samples-boot-oauth2login-webflux.gradle b/samples/boot/oauth2login-webflux/spring-security-samples-boot-oauth2login-webflux.gradle new file mode 100644 index 0000000000..933d9079e9 --- /dev/null +++ b/samples/boot/oauth2login-webflux/spring-security-samples-boot-oauth2login-webflux.gradle @@ -0,0 +1,17 @@ +apply plugin: 'io.spring.convention.spring-sample-boot' + +ext['thymeleaf.version'] = '3.0.9.RELEASE' + +dependencies { + compile project(':spring-security-config') + compile project(':spring-security-oauth2-client') + compile project(':spring-security-oauth2-jose') + compile 'org.springframework.boot:spring-boot-starter-thymeleaf' + compile 'org.springframework.boot:spring-boot-starter-webflux' + compile 'org.thymeleaf.extras:thymeleaf-extras-springsecurity4' + compile 'io.projectreactor.ipc:reactor-netty' + + testCompile project(':spring-security-test') + testCompile 'net.sourceforge.htmlunit:htmlunit' + testCompile 'org.springframework.boot:spring-boot-starter-test' +} diff --git a/samples/boot/oauth2login-webflux/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ReactiveOAuth2ClientAutoConfiguration.java b/samples/boot/oauth2login-webflux/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ReactiveOAuth2ClientAutoConfiguration.java new file mode 100644 index 0000000000..dd3d788fe9 --- /dev/null +++ b/samples/boot/oauth2login-webflux/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ReactiveOAuth2ClientAutoConfiguration.java @@ -0,0 +1,43 @@ +/* + * Copyright 2012-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.autoconfigure.security.oauth2.client; + +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.oauth2.client.registration.ClientRegistration; + +/** + * {@link EnableAutoConfiguration Auto-configuration} for OAuth client support. + * + * @author Madhura Bhave + * @author Phillip Webb + * @since 2.0.0 + */ +@Configuration +@AutoConfigureBefore(name = "org.springframework.boot.autoconfigure.security.reactive.WebFluxSecurityConfiguration") +@ConditionalOnClass({ EnableWebFluxSecurity.class, ClientRegistration.class }) +@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) +@Import({ ReactiveOAuth2ClientRegistrationRepositoryConfiguration.class, + ReactiveOAuth2WebSecurityConfiguration.class }) +public class ReactiveOAuth2ClientAutoConfiguration { + +} diff --git a/samples/boot/oauth2login-webflux/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ReactiveOAuth2ClientRegistrationRepositoryConfiguration.java b/samples/boot/oauth2login-webflux/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ReactiveOAuth2ClientRegistrationRepositoryConfiguration.java new file mode 100644 index 0000000000..abd5e767a1 --- /dev/null +++ b/samples/boot/oauth2login-webflux/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ReactiveOAuth2ClientRegistrationRepositoryConfiguration.java @@ -0,0 +1,57 @@ +/* + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.autoconfigure.security.oauth2.client; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository; +import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; + +/** + * {@link Configuration} used to map {@link OAuth2ClientProperties} to client + * registrations. + * + * @author Madhura Bhave + * @author Phillip Webb + */ +@Configuration +@EnableConfigurationProperties(OAuth2ClientProperties.class) +@Conditional(OAuth2ClientRegistrationRepositoryConfiguration.ClientsConfiguredCondition.class) +class ReactiveOAuth2ClientRegistrationRepositoryConfiguration { + + private final OAuth2ClientProperties properties; + + ReactiveOAuth2ClientRegistrationRepositoryConfiguration(OAuth2ClientProperties properties) { + this.properties = properties; + } + + @Bean + @ConditionalOnMissingBean(ReactiveClientRegistrationRepository.class) + public InMemoryReactiveClientRegistrationRepository clientRegistrationRepository() { + List registrations = new ArrayList<>( + OAuth2ClientPropertiesRegistrationAdapter + .getClientRegistrations(this.properties).values()); + return new InMemoryReactiveClientRegistrationRepository(registrations); + } +} diff --git a/samples/boot/oauth2login-webflux/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ReactiveOAuth2WebSecurityConfiguration.java b/samples/boot/oauth2login-webflux/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ReactiveOAuth2WebSecurityConfiguration.java new file mode 100644 index 0000000000..13234672d6 --- /dev/null +++ b/samples/boot/oauth2login-webflux/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/ReactiveOAuth2WebSecurityConfiguration.java @@ -0,0 +1,46 @@ +/* + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.boot.autoconfigure.security.oauth2.client; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.oauth2.client.InMemoryReactiveOAuth2AuthorizedClientService; +import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService; +import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; + +/** + * {@link WebSecurityConfigurerAdapter} to add OAuth client support. + * + * @author Madhura Bhave + * @author Phillip Webb + * @since 2.0.0 + */ +@Configuration +@ConditionalOnBean(ReactiveClientRegistrationRepository.class) +class ReactiveOAuth2WebSecurityConfiguration { + + @Bean + @ConditionalOnMissingBean + public ReactiveOAuth2AuthorizedClientService authorizedClientService( + ReactiveClientRegistrationRepository clientRegistrationRepository) { + return new InMemoryReactiveOAuth2AuthorizedClientService(clientRegistrationRepository); + } + +} diff --git a/samples/boot/oauth2login-webflux/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/package-info.java b/samples/boot/oauth2login-webflux/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/package-info.java new file mode 100644 index 0000000000..6cefe5bb02 --- /dev/null +++ b/samples/boot/oauth2login-webflux/src/main/java/org/springframework/boot/autoconfigure/security/oauth2/client/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright 2012-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Auto-configuration for Spring Security's Reactive OAuth 2 client. This will be merged into Spring Boot 2.1. + */ +package org.springframework.boot.autoconfigure.security.oauth2.client; diff --git a/samples/boot/oauth2login-webflux/src/main/java/sample/ReactiveOAuth2LoginApplication.java b/samples/boot/oauth2login-webflux/src/main/java/sample/ReactiveOAuth2LoginApplication.java new file mode 100644 index 0000000000..86412e1b22 --- /dev/null +++ b/samples/boot/oauth2login-webflux/src/main/java/sample/ReactiveOAuth2LoginApplication.java @@ -0,0 +1,31 @@ +/* + * Copyright 2002-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package sample; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @author Rob Winch + */ +@SpringBootApplication +public class ReactiveOAuth2LoginApplication { + + public static void main(String[] args) { + SpringApplication.run(ReactiveOAuth2LoginApplication.class, args); + } + +} diff --git a/samples/boot/oauth2login-webflux/src/main/java/sample/web/OAuth2LoginController.java b/samples/boot/oauth2login-webflux/src/main/java/sample/web/OAuth2LoginController.java new file mode 100644 index 0000000000..d3bcaf342e --- /dev/null +++ b/samples/boot/oauth2login-webflux/src/main/java/sample/web/OAuth2LoginController.java @@ -0,0 +1,74 @@ +/* + * Copyright 2002-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package sample.web; + +import java.util.Map; + +import org.springframework.http.HttpHeaders; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; +import org.springframework.security.oauth2.client.annotation.OAuth2Client; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.reactive.function.client.ClientRequest; +import org.springframework.web.reactive.function.client.ExchangeFilterFunction; +import org.springframework.web.reactive.function.client.WebClient; + +import reactor.core.publisher.Mono; + +/** + * @author Rob Winch + */ +@Controller +public class OAuth2LoginController { + + @GetMapping("/") + public String index(Model model, @OAuth2Client OAuth2AuthorizedClient authorizedClient) { + model.addAttribute("userName", authorizedClient.getPrincipalName()); + model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName()); + return "index"; + } + + @GetMapping("/userinfo") + public String userinfo(Model model, @OAuth2Client OAuth2AuthorizedClient authorizedClient) { + Mono userAttributes = Mono.empty(); + String userInfoEndpointUri = authorizedClient.getClientRegistration() + .getProviderDetails().getUserInfoEndpoint().getUri(); + if (!StringUtils.isEmpty(userInfoEndpointUri)) { // userInfoEndpointUri is optional for OIDC Clients + userAttributes = WebClient.builder() + .filter(oauth2Credentials(authorizedClient)) + .build() + .get() + .uri(userInfoEndpointUri) + .retrieve() + .bodyToMono(Map.class); + } + model.addAttribute("userAttributes", userAttributes); + return "userinfo"; + } + + private ExchangeFilterFunction oauth2Credentials(OAuth2AuthorizedClient authorizedClient) { + return ExchangeFilterFunction.ofRequestProcessor( + clientRequest -> { + ClientRequest authorizedRequest = ClientRequest.from(clientRequest) + .header(HttpHeaders.AUTHORIZATION, "Bearer " + authorizedClient.getAccessToken().getTokenValue()) + .build(); + return Mono.just(authorizedRequest); + }); + } +} diff --git a/samples/boot/oauth2login-webflux/src/main/resources/META-INF/spring.factories b/samples/boot/oauth2login-webflux/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000000..58f06009ff --- /dev/null +++ b/samples/boot/oauth2login-webflux/src/main/resources/META-INF/spring.factories @@ -0,0 +1,3 @@ +# Auto Configure +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +org.springframework.boot.autoconfigure.security.oauth2.client.ReactiveOAuth2ClientAutoConfiguration diff --git a/samples/boot/oauth2login-webflux/src/main/resources/application.yml b/samples/boot/oauth2login-webflux/src/main/resources/application.yml new file mode 100644 index 0000000000..73b08fbd83 --- /dev/null +++ b/samples/boot/oauth2login-webflux/src/main/resources/application.yml @@ -0,0 +1,35 @@ +server: + port: 8080 + +logging: + level: + root: INFO + org.springframework.web: INFO + org.springframework.security: INFO +# org.springframework.boot.autoconfigure: DEBUG + +spring: + thymeleaf: + cache: false + security: + oauth2: + client: + registration: + google: + client-id: your-app-client-id + client-secret: your-app-client-secret + github: + client-id: your-app-client-id + client-secret: your-app-client-secret + facebook: + client-id: your-app-client-id + client-secret: your-app-client-secret + okta: + client-id: your-app-client-id + client-secret: your-app-client-secret + provider: + okta: + 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 + jwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys diff --git a/samples/boot/oauth2login-webflux/src/main/resources/templates/index.html b/samples/boot/oauth2login-webflux/src/main/resources/templates/index.html new file mode 100644 index 0000000000..19165ae1c3 --- /dev/null +++ b/samples/boot/oauth2login-webflux/src/main/resources/templates/index.html @@ -0,0 +1,46 @@ + + + + + + Spring Security - OAuth 2.0 Login + + + +
+
+ User: +
+
 
+
+ Log Out +
+
+

OAuth 2.0 Login with Spring Security

+
+ You are successfully logged in + via the OAuth 2.0 Client +
+
 
+ + + diff --git a/samples/boot/oauth2login-webflux/src/main/resources/templates/userinfo.html b/samples/boot/oauth2login-webflux/src/main/resources/templates/userinfo.html new file mode 100644 index 0000000000..be4efb2800 --- /dev/null +++ b/samples/boot/oauth2login-webflux/src/main/resources/templates/userinfo.html @@ -0,0 +1,38 @@ + + + + + + Spring Security - OAuth 2.0 User Info + + + +
+

OAuth 2.0 User Info

+
+ User Attributes: +
    +
  • + : +
  • +
+
+ +