Skip to content

Commit 62d01d2

Browse files
committed
Add oauth2login xml sample
Fixes gh-8060
1 parent 558924e commit 62d01d2

File tree

8 files changed

+567
-0
lines changed

8 files changed

+567
-0
lines changed

samples/xml/oauth2login/README.adoc

Lines changed: 278 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
1+
= OAuth 2.0 Login Sample
2+
3+
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.
4+
5+
The following sections provide detailed steps for setting up OAuth 2.0 Login for these Providers:
6+
7+
* <<google-login, Google>>
8+
* <<github-login, GitHub>>
9+
* <<facebook-login, Facebook>>
10+
* <<okta-login, Okta>>
11+
12+
[[google-login]]
13+
== Login with Google
14+
15+
This section shows how to configure the sample application using Google as the Authentication Provider and covers the following topics:
16+
17+
* <<google-initial-setup,Initial setup>>
18+
* <<google-redirect-uri,Setting the redirect URI>>
19+
* <<google-application-config,Configure security.xml>>
20+
* <<google-boot-application,Deploy and start the application>>
21+
22+
[[google-initial-setup]]
23+
=== Initial setup
24+
25+
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.
26+
27+
NOTE: https://developers.google.com/identity/protocols/OpenIDConnect[Google's OAuth 2.0 implementation] for authentication conforms to the
28+
https://openid.net/connect/[OpenID Connect 1.0] specification and is https://openid.net/certification/[OpenID Certified].
29+
30+
Follow the instructions on the https://developers.google.com/identity/protocols/OpenIDConnect[OpenID Connect] page, starting in the section, "Setting up OAuth 2.0".
31+
32+
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.
33+
34+
[[google-redirect-uri]]
35+
=== Setting the redirect URI
36+
37+
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
38+
and have granted access to the OAuth Client _(created in the previous step)_ on the Consent page.
39+
40+
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`.
41+
42+
TIP: The default redirect URI template is `{baseUrl}/login/oauth2/code/{registrationId}`.
43+
The *_registrationId_* is a unique identifier for the `ClientRegistration`.
44+
45+
IMPORTANT: If the application is running behind a proxy server, it is recommended to check https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#appendix-proxy-server[Proxy Server Configuration] to ensure the application is correctly configured.
46+
Also, see the supported https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#oauth2Client-auth-code-redirect-uri[`URI` template variables] for `redirect-uri`.
47+
48+
[[google-application-config]]
49+
=== Configure security.xml
50+
51+
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:
52+
53+
. Go to `security.xml` and set the following configuration:
54+
+
55+
[source,xml]
56+
----
57+
<client-registration registration-id="google"
58+
client-id="google-client-id"
59+
client-secret="google-client-secret"
60+
provider-id="google"/>
61+
----
62+
63+
. Replace the values in the `client-id` and `client-secret` attributes with the OAuth 2.0 credentials you created earlier.
64+
65+
[[google-boot-application]]
66+
=== Deploy and start the application
67+
68+
Deploy the WAR to a `Servlet` container and then go to `http://localhost:8080`.
69+
You are then redirected to the default _auto-generated_ login page, which displays a link for Google.
70+
71+
Click on the Google link, and you are then redirected to Google for authentication.
72+
73+
After authenticating with your Google account credentials, the next page presented to you is the Consent screen.
74+
The Consent screen asks you to either allow or deny access to the OAuth Client you created earlier.
75+
Click *Allow* to authorize the OAuth Client to access your email address and basic profile information.
76+
77+
At this point, the OAuth Client retrieves your email address and basic profile information
78+
from the https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] and establishes an authenticated session.
79+
80+
[[github-login]]
81+
== Login with GitHub
82+
83+
This section shows how to configure the sample application using GitHub as the Authentication Provider and covers the following topics:
84+
85+
* <<github-register-application,Register OAuth application>>
86+
* <<github-application-config,Configure security.xml>>
87+
* <<github-boot-application,Deploy and start the application>>
88+
89+
[[github-register-application]]
90+
=== Register OAuth application
91+
92+
To use GitHub's OAuth 2.0 authentication system for login, you must https://github.com/settings/applications/new[Register a new OAuth application].
93+
94+
When registering the OAuth application, ensure the *Authorization callback URL* is set to `http://localhost:8080/login/oauth2/code/github`.
95+
96+
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
97+
and have granted access to the OAuth application on the _Authorize application_ page.
98+
99+
TIP: The default redirect URI template is `{baseUrl}/login/oauth2/code/{registrationId}`.
100+
The *_registrationId_* is a unique identifier for the `ClientRegistration`.
101+
102+
IMPORTANT: If the application is running behind a proxy server, it is recommended to check https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#appendix-proxy-server[Proxy Server Configuration] to ensure the application is correctly configured.
103+
Also, see the supported https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#oauth2Client-auth-code-redirect-uri[`URI` template variables] for `redirect-uri`.
104+
105+
[[github-application-config]]
106+
=== Configure security.xml
107+
108+
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:
109+
110+
. Go to `security.xml` and set the following configuration:
111+
+
112+
[source,xml]
113+
----
114+
<client-registration registration-id="github"
115+
client-id="github-client-id"
116+
client-secret="github-client-secret"
117+
provider-id="github"/>
118+
----
119+
120+
. Replace the values in the `client-id` and `client-secret` attributes with the OAuth 2.0 credentials you created earlier.
121+
122+
[[github-boot-application]]
123+
=== Deploy and start the application
124+
125+
Deploy the WAR to a `Servlet` container and then go to `http://localhost:8080`.
126+
You are then redirected to the default _auto-generated_ login page, which displays a link for GitHub.
127+
128+
Click on the GitHub link, and you are then redirected to GitHub for authentication.
129+
130+
After authenticating with your GitHub credentials, the next page presented to you is "Authorize application".
131+
This page will ask you to *Authorize* the application you created in the previous step.
132+
Click _Authorize application_ to allow the OAuth application to access your personal user data information.
133+
134+
At this point, the OAuth Client retrieves your personal user information
135+
from the UserInfo Endpoint and establishes an authenticated session.
136+
137+
[TIP]
138+
For detailed information returned from the UserInfo Endpoint, see the API documentation
139+
for https://developer.github.com/v3/users/#get-the-authenticated-user["Get the authenticated user"].
140+
141+
[[facebook-login]]
142+
== Login with Facebook
143+
144+
This section shows how to configure the sample application using Facebook as the Authentication Provider and covers the following topics:
145+
146+
* <<facebook-register-application,Add a New App>>
147+
* <<facebook-application-config,Configure security.xml>>
148+
* <<facebook-boot-application,Deploy and start the application>>
149+
150+
[[facebook-register-application]]
151+
=== Add a New App
152+
153+
To use Facebook's OAuth 2.0 authentication system for login, you must first https://developers.facebook.com/apps[Add a New App].
154+
155+
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".
156+
157+
NOTE: The selection for the _Category_ field is not relevant but it's a required field - select "Local".
158+
159+
The next page presented is "Product Setup". Click the "Get Started" button for the *Facebook Login* product.
160+
In the left sidebar, under _Products -> Facebook Login_, select _Settings_.
161+
162+
For the field *Valid OAuth redirect URIs*, enter `http://localhost:8080/login/oauth2/code/facebook` then click _Save Changes_.
163+
164+
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
165+
and have granted access to the application on the _Authorize application_ page.
166+
167+
TIP: The default redirect URI template is `{baseUrl}/login/oauth2/code/{registrationId}`.
168+
The *_registrationId_* is a unique identifier for the `ClientRegistration`.
169+
170+
IMPORTANT: If the application is running behind a proxy server, it is recommended to check https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#appendix-proxy-server[Proxy Server Configuration] to ensure the application is correctly configured.
171+
Also, see the supported https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#oauth2Client-auth-code-redirect-uri[`URI` template variables] for `redirect-uri`.
172+
173+
[[facebook-application-config]]
174+
=== Configure security.xml
175+
176+
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:
177+
178+
. Go to `security.xml` and set the following configuration:
179+
+
180+
[source,xml]
181+
----
182+
<client-registration registration-id="facebook"
183+
client-id="facebook-client-id"
184+
client-secret="facebook-client-secret"
185+
provider-id="facebook"/>
186+
----
187+
188+
. Replace the values in the `client-id` and `client-secret` attributes with the OAuth 2.0 credentials you created earlier.
189+
190+
[[facebook-boot-application]]
191+
=== Deploy and start the application
192+
193+
Deploy the WAR to a `Servlet` container and then go to `http://localhost:8080`.
194+
You are then redirected to the default _auto-generated_ login page, which displays a link for Facebook.
195+
196+
Click on the Facebook link, and you are then redirected to Facebook for authentication.
197+
198+
After authenticating with your Facebook credentials, the next page presented to you is "Authorize application".
199+
This page will ask you to *Authorize* the application you created in the previous step.
200+
Click _Authorize application_ to allow the OAuth application to access your _public profile_ and _email address_ information.
201+
202+
At this point, the OAuth Client retrieves your personal user information
203+
from the UserInfo Endpoint and establishes an authenticated session.
204+
205+
[[okta-login]]
206+
== Login with Okta
207+
208+
This section shows how to configure the sample application using Okta as the Authentication Provider and covers the following topics:
209+
210+
* <<okta-register-application,Add Application>>
211+
* <<okta-assign-application-people,Assign Application to People>>
212+
* <<okta-application-config,Configure security.xml>>
213+
* <<okta-boot-application,Deploy and start the application>>
214+
215+
[[okta-register-application]]
216+
=== Add Application
217+
218+
To use Okta's OAuth 2.0 authentication system for login, you must first https://www.okta.com/developer/signup[create a developer account].
219+
220+
Sign in to your account sub-domain and navigate to _Applications -> Applications_ and then select the "Add Application" button.
221+
From the "Add Application" page, select the "Create New App" button and enter the following:
222+
223+
* *Platform:* Web
224+
* *Sign on method:* OpenID Connect
225+
226+
Select the _Create_ button.
227+
On the "General Settings" page, enter the Application Name (for example, "Spring Security Okta Login") and then select the _Next_ button.
228+
On the "Configure OpenID Connect" page, enter `http://localhost:8080/login/oauth2/code/okta` for the field *Redirect URIs* and then select _Finish_.
229+
230+
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
231+
and have granted access to the application on the _Authorize application_ page.
232+
233+
TIP: The default redirect URI template is `{baseUrl}/login/oauth2/code/{registrationId}`.
234+
The *_registrationId_* is a unique identifier for the `ClientRegistration`.
235+
236+
IMPORTANT: If the application is running behind a proxy server, it is recommended to check https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#appendix-proxy-server[Proxy Server Configuration] to ensure the application is correctly configured.
237+
Also, see the supported https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#oauth2Client-auth-code-redirect-uri[`URI` template variables] for `redirect-uri`.
238+
239+
[[okta-assign-application-people]]
240+
=== Assign Application to People
241+
242+
From the "General" tab of the application, select the "Assignments" tab and then select the _Assign_ button.
243+
Select _Assign to People_ and assign your account to the application. Then select the _Save and Go Back_ button.
244+
245+
[[okta-application-config]]
246+
=== Configure security.xml
247+
248+
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:
249+
250+
. Go to `security.xml` and set the following configuration:
251+
+
252+
[source,xml]
253+
----
254+
<client-registration registration-id="okta"
255+
client-id="okta-client-id"
256+
client-secret="okta-client-secret"
257+
provider-id="okta"/>
258+
259+
<provider provider-id="okta"
260+
authorization-uri="https://your-subdomain.oktapreview.com/oauth2/v1/authorize"
261+
token-uri="https://your-subdomain.oktapreview.com/oauth2/v1/token"
262+
user-info-uri="https://your-subdomain.oktapreview.com/oauth2/v1/userinfo"
263+
jwk-set-uri="https://your-subdomain.oktapreview.com/oauth2/v1/keys"/>
264+
----
265+
266+
. Replace the values in the `client-id` and `client-secret` attributes with the OAuth 2.0 credentials you created earlier.
267+
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.
268+
269+
[[okta-boot-application]]
270+
=== Deploy and start the application
271+
272+
Deploy the WAR to a `Servlet` container and then go to `http://localhost:8080`.
273+
You are then redirected to the default _auto-generated_ login page, which displays a link for Okta.
274+
275+
Click on the Okta link, and you are then redirected to Okta for authentication.
276+
277+
After authenticating with your Okta account credentials, the OAuth Client retrieves your email address and basic profile information
278+
from the https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] and establishes an authenticated session.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
apply plugin: 'io.spring.convention.spring-sample-war'
2+
3+
dependencies {
4+
compile 'org.springframework:spring-context'
5+
compile 'org.springframework:spring-webmvc'
6+
compile project(':spring-security-config')
7+
compile project(':spring-security-web')
8+
compile project(':spring-security-oauth2-client')
9+
compile project(':spring-security-oauth2-jose')
10+
compile 'com.fasterxml.jackson.core:jackson-databind'
11+
compile 'org.thymeleaf:thymeleaf-spring5'
12+
compile 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5:3.0.4.RELEASE'
13+
14+
testCompile project(':spring-security-test')
15+
}
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
/*
2+
* Copyright 2002-2020 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package sample.config;
17+
18+
import org.springframework.beans.BeansException;
19+
import org.springframework.beans.factory.annotation.Autowired;
20+
import org.springframework.context.ApplicationContext;
21+
import org.springframework.context.ApplicationContextAware;
22+
import org.springframework.context.annotation.Bean;
23+
import org.springframework.context.annotation.Configuration;
24+
import org.springframework.context.expression.BeanFactoryResolver;
25+
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
26+
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
27+
import org.springframework.security.oauth2.client.web.method.annotation.OAuth2AuthorizedClientArgumentResolver;
28+
import org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver;
29+
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
30+
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
31+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
32+
import org.thymeleaf.spring5.SpringTemplateEngine;
33+
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
34+
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
35+
import org.thymeleaf.templatemode.TemplateMode;
36+
37+
import java.util.List;
38+
39+
/**
40+
* @author Joe Grandja
41+
*/
42+
@Configuration
43+
@EnableWebMvc
44+
public class WebConfig implements WebMvcConfigurer, ApplicationContextAware {
45+
private ApplicationContext context;
46+
private ClientRegistrationRepository clientRegistrationRepository;
47+
private OAuth2AuthorizedClientRepository authorizedClientRepository;
48+
49+
@Override
50+
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
51+
// @AuthenticationPrincipal
52+
AuthenticationPrincipalArgumentResolver principalArgumentResolver =
53+
new AuthenticationPrincipalArgumentResolver();
54+
principalArgumentResolver.setBeanResolver(new BeanFactoryResolver(
55+
this.context.getAutowireCapableBeanFactory()));
56+
resolvers.add(principalArgumentResolver);
57+
58+
// @RegisteredOAuth2AuthorizedClient
59+
resolvers.add(new OAuth2AuthorizedClientArgumentResolver(
60+
this.clientRegistrationRepository, this.authorizedClientRepository));
61+
}
62+
63+
@Override
64+
public void setApplicationContext(ApplicationContext context) throws BeansException {
65+
this.context = context;
66+
}
67+
68+
@Autowired
69+
public void setClientRegistrationRepository(ClientRegistrationRepository clientRegistrationRepository) {
70+
this.clientRegistrationRepository = clientRegistrationRepository;
71+
}
72+
73+
@Autowired
74+
public void setAuthorizedClientRepository(OAuth2AuthorizedClientRepository authorizedClientRepository) {
75+
this.authorizedClientRepository = authorizedClientRepository;
76+
}
77+
78+
@Bean
79+
public SpringResourceTemplateResolver templateResolver() {
80+
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
81+
templateResolver.setApplicationContext(this.context);
82+
templateResolver.setPrefix("/WEB-INF/templates/");
83+
templateResolver.setSuffix(".html");
84+
templateResolver.setTemplateMode(TemplateMode.HTML);
85+
templateResolver.setCacheable(true);
86+
return templateResolver;
87+
}
88+
89+
@Bean
90+
public SpringTemplateEngine templateEngine() {
91+
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
92+
templateEngine.setTemplateResolver(templateResolver());
93+
templateEngine.setEnableSpringELCompiler(true);
94+
return templateEngine;
95+
}
96+
97+
@Bean
98+
public ThymeleafViewResolver viewResolver() {
99+
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
100+
viewResolver.setTemplateEngine(templateEngine());
101+
return viewResolver;
102+
}
103+
}

0 commit comments

Comments
 (0)