README.adoc 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. = OAuth 2.0 Login Sample
  2. Joe Grandja
  3. :toc:
  4. :security-site-url: https://projects.spring.io/spring-security/
  5. [.lead]
  6. This guide will walk you through the steps for setting up the sample application with OAuth 2.0 Login using an external _OAuth 2.0_ or _OpenID Connect 1.0_ Provider.
  7. The sample application is built with *Spring Boot 1.5* and the *spring-security-oauth2-client* module that is new in {security-site-url}[Spring Security 5.0].
  8. The following sections outline detailed steps for setting up OAuth 2.0 Login with these Providers:
  9. * <<google-login, Google>>
  10. * <<github-login, GitHub>>
  11. * <<facebook-login, Facebook>>
  12. * <<okta-login, Okta>>
  13. NOTE: The _"authentication flow"_ is realized using the *Authorization Code Grant*, as specified in the https://tools.ietf.org/html/rfc6749#section-4.1[OAuth 2.0 Authorization Framework]
  14. and http://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth[OpenID Connect Core 1.0] specifications.
  15. [[sample-app-content]]
  16. == Sample application content
  17. The sample application contains the following package structure and artifacts:
  18. *sample*
  19. [circle]
  20. * _OAuth2LoginApplication_ - the main class for the _Spring application_.
  21. ** *user*
  22. *** _GitHubOAuth2User_ - a custom _OAuth2User_ for <<github-login, GitHub Login>>.
  23. ** *web*
  24. *** _MainController_ - the root controller that displays user information after a successful login.
  25. *org.springframework.boot.autoconfigure.security.oauth2.client*
  26. [circle]
  27. * <<client-registration-auto-configuration-class, _ClientRegistrationAutoConfiguration_>> - a Spring Boot auto-configuration class
  28. that automatically registers a _ClientRegistrationRepository_ bean in the _ApplicationContext_.
  29. * <<oauth2-login-auto-configuration-class, _OAuth2LoginAutoConfiguration_>> - a Spring Boot auto-configuration class that automatically enables OAuth 2.0 Login.
  30. WARNING: The Spring Boot auto-configuration classes (and dependent resources) will eventually _live_ in the *Spring Boot Security Starter*.
  31. NOTE: See <<oauth2-login-auto-configuration, OAuth 2.0 Login auto-configuration>> for a detailed overview of the auto-configuration classes.
  32. [[google-login]]
  33. == Setting up *_Login with Google_*
  34. The goal for this section of the guide is to setup login using Google as the _Authentication Provider_.
  35. NOTE: https://developers.google.com/identity/protocols/OpenIDConnect[Google's OAuth 2.0 implementation] for authentication conforms to the
  36. http://openid.net/connect/[OpenID Connect] specification and is http://openid.net/certification/[OpenID Certified].
  37. [[google-login-register-credentials]]
  38. === Register OAuth 2.0 credentials
  39. In order 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.
  40. Follow the instructions on the https://developers.google.com/identity/protocols/OpenIDConnect[OpenID Connect] page starting in the section *_"Setting up OAuth 2.0"_*.
  41. After completing the sub-section, *_"Obtain OAuth 2.0 credentials"_*, you should have created a new *OAuth Client* with credentials consisting of a *Client ID* and *Client Secret*.
  42. [[google-login-redirect-uri]]
  43. === Setting the redirect URI
  44. The redirect URI is the path in the sample application that the end-user's user-agent is redirected back to after they have authenticated with Google
  45. and have granted access to the OAuth Client _(created from the <<google-login-register-credentials, previous step>>)_ on the *Consent screen* page.
  46. For the sub-section, *_"Set a redirect URI"_*, ensure the *Authorised redirect URIs* is set to *http://localhost:8080/oauth2/authorize/code/google*
  47. TIP: The default redirect URI is *_"{scheme}://{serverName}:{serverPort}/oauth2/authorize/code/{registrationId}"_*.
  48. See <<oauth2-client-properties, OAuth client properties>> for more details on this default.
  49. [[google-login-configure-application-yml]]
  50. === Configuring application.yml
  51. Now that we have created a new OAuth Client with Google, we need to configure the sample application to use this OAuth Client for the _authentication flow_.
  52. Go to *_src/main/resources_* and edit *application.yml*. Add the following configuration:
  53. [source,yaml]
  54. ----
  55. security:
  56. oauth2:
  57. client:
  58. google:
  59. client-id: ${client-id}
  60. client-secret: ${client-secret}
  61. ----
  62. Replace *${client-id}* and *${client-secret}* with the OAuth 2.0 credentials created in the previous section <<google-login-register-credentials, Register OAuth 2.0 credentials>>.
  63. [TIP]
  64. .OAuth client properties
  65. ====
  66. . *security.oauth2.client* is the *_base property prefix_* for OAuth client properties.
  67. . Just below the *_base property prefix_* is the *_client property key_*, for example *security.oauth2.client.registrations.google*.
  68. . At the base of the *_client property key_* are the properties for specifying the configuration for an OAuth Client.
  69. A list of these properties are detailed in <<oauth2-client-properties, OAuth client properties>>.
  70. ====
  71. [[google-login-run-sample]]
  72. === Running the sample
  73. Launch the Spring Boot application by running *_sample.OAuth2LoginApplication_*.
  74. After the application successfully starts up, go to http://localhost:8080. You'll then be redirected to http://localhost:8080/login, which will display an _auto-generated login page_ with an anchor link for *Google*.
  75. Click through on the Google link and you'll be redirected to Google for authentication.
  76. After you authenticate using your Google credentials, the next page presented to you will be the *Consent screen*.
  77. The Consent screen will ask you to either *_Allow_* or *_Deny_* access to the OAuth Client you created in the previous step <<google-login-register-credentials, Register OAuth 2.0 credentials>>.
  78. Click *_Allow_* to authorize the OAuth Client to access your _email address_ and _basic profile_ information.
  79. At this point, the OAuth Client will retrieve your email address and basic profile information from the http://openid.net/specs/openid-connect-core-1_0.html#UserInfo[*UserInfo Endpoint*] and establish an _authenticated session_.
  80. The home page will then be displayed showing the user attributes retrieved from the UserInfo Endpoint, for example, name, email, profile, sub, etc.
  81. [[github-login]]
  82. == Setting up *_Login with GitHub_*
  83. The goal for this section of the guide is to setup login using GitHub as the _Authentication Provider_.
  84. NOTE: https://developer.github.com/v3/oauth/[GitHub's OAuth 2.0 implementation] supports the standard
  85. https://tools.ietf.org/html/rfc6749#section-4.1[authorization code grant type].
  86. However, it *does not* implement the _OpenID Connect Core 1.0_ authorization code flow.
  87. [[github-login-register-application]]
  88. === Register OAuth application
  89. In order to use GitHub's OAuth 2.0 authentication system for login, you must https://github.com/settings/applications/new[_Register a new OAuth application_].
  90. While registering your application, ensure the *Authorization callback URL* is set to *http://localhost:8080/oauth2/authorize/code/github*.
  91. NOTE: The *Authorization callback URL* (or redirect URI) is the path in the sample application that the end-user's user-agent is redirected back to after they have authenticated with GitHub
  92. and have granted access to the OAuth application on the *Authorize application* page.
  93. TIP: The default redirect URI is *_"{scheme}://{serverName}:{serverPort}/oauth2/authorize/code/{registrationId}"_*.
  94. See <<oauth2-client-properties, OAuth client properties>> for more details on this default.
  95. After completing the registration, you should have created a new *OAuth Application* with credentials consisting of a *Client ID* and *Client Secret*.
  96. [[github-login-configure-application-yml]]
  97. === Configuring application.yml
  98. Now that we have created a new OAuth application with GitHub, we need to configure the sample application to use this OAuth application (client) for the _authentication flow_.
  99. Go to *_src/main/resources_* and edit *application.yml*. Add the following configuration:
  100. [source,yaml]
  101. ----
  102. security:
  103. oauth2:
  104. client:
  105. github:
  106. client-id: ${client-id}
  107. client-secret: ${client-secret}
  108. ----
  109. Replace *${client-id}* and *${client-secret}* with the OAuth 2.0 credentials created in the previous section <<github-login-register-application, Register OAuth application>>.
  110. [TIP]
  111. .OAuth client properties
  112. ====
  113. . *security.oauth2.client* is the *_base property prefix_* for OAuth client properties.
  114. . Just below the *_base property prefix_* is the *_client property key_*, for example *security.oauth2.client.registrations.github*.
  115. . At the base of the *_client property key_* are the properties for specifying the configuration for an OAuth Client.
  116. A list of these properties are detailed in <<oauth2-client-properties, OAuth client properties>>.
  117. ====
  118. [[github-login-run-sample]]
  119. === Running the sample
  120. Launch the Spring Boot application by running *_sample.OAuth2LoginApplication_*.
  121. After the application successfully starts up, go to http://localhost:8080. You'll then be redirected to http://localhost:8080/login, which will display an _auto-generated login page_ with an anchor link for *GitHub*.
  122. Click through on the GitHub link and you'll be redirected to GitHub for authentication.
  123. After you authenticate using your GitHub credentials, the next page presented to you is *Authorize application*.
  124. This page will ask you to *Authorize* the application you created in the previous step <<github-login-register-application, Register OAuth application>>.
  125. Click *_Authorize application_* to allow the OAuth application to access your _Personal user data_ information.
  126. At this point, the OAuth application will retrieve your personal user information from the *UserInfo Endpoint* and establish an _authenticated session_.
  127. The home page will then be displayed showing the user attributes retrieved from the UserInfo Endpoint, for example, id, name, email, login, etc.
  128. TIP: For detailed information returned from the *UserInfo Endpoint* see the API documentation
  129. for https://developer.github.com/v3/users/#get-the-authenticated-user[_Get the authenticated user_].
  130. [[facebook-login]]
  131. == Setting up *_Login with Facebook_*
  132. The goal for this section of the guide is to setup login using Facebook as the _Authentication Provider_.
  133. NOTE: Facebook provides support for developers to https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow[_Manually Build a Login Flow_].
  134. The _login flow_ uses browser-based redirects, which essentially implements the https://tools.ietf.org/html/rfc6749#section-4.1[authorization code grant type].
  135. (NOTE: Facebook partially implements the _OAuth 2.0 Authorization Framework_, however, it *does not* implement the _OpenID Connect Core 1.0_ authorization code flow.)
  136. [[facebook-login-register-application]]
  137. === Add a New App
  138. In order to use Facebook's OAuth 2.0 authentication system for login, you must first https://developers.facebook.com/apps[_Add a New App_].
  139. After clicking _"Create a New App"_, the _"Create a New App ID"_ page is presented. Enter the Display Name, Contact Email, Category and then click _"Create App ID"_.
  140. NOTE: The selection for the _Category_ field is not relevant but it's a required field - select _"Local"_.
  141. 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_*.
  142. For the field *Valid OAuth redirect URIs*, enter *http://localhost:8080/oauth2/authorize/code/facebook* then click _"Save Changes"_.
  143. NOTE: The *OAuth redirect URI* is the path in the sample application that the end-user's user-agent is redirected back to after they have authenticated with Facebook
  144. and have granted access to the application on the *Authorize application* page.
  145. TIP: The default redirect URI is *_"{scheme}://{serverName}:{serverPort}/oauth2/authorize/code/{registrationId}"_*.
  146. See <<oauth2-client-properties, OAuth client properties>> for more details on this default.
  147. Your application has now been assigned new OAuth 2.0 credentials under *App ID* and *App Secret*.
  148. [[facebook-login-configure-application-yml]]
  149. === Configuring application.yml
  150. Now that we have created a new application with Facebook, we need to configure the sample application to use this application (client) for the _authentication flow_.
  151. Go to *_src/main/resources_* and edit *application.yml*. Add the following configuration:
  152. [source,yaml]
  153. ----
  154. security:
  155. oauth2:
  156. client:
  157. facebook:
  158. client-id: ${app-id}
  159. client-secret: ${app-secret}
  160. ----
  161. Replace *${app-id}* and *${app-secret}* with the OAuth 2.0 credentials created in the previous section <<facebook-login-register-application, Add a New App>>.
  162. [TIP]
  163. .OAuth client properties
  164. ====
  165. . *security.oauth2.client* is the *_base property prefix_* for OAuth client properties.
  166. . Just below the *_base property prefix_* is the *_client property key_*, for example *security.oauth2.client.registrations.facebook*.
  167. . At the base of the *_client property key_* are the properties for specifying the configuration for an OAuth Client.
  168. A list of these properties are detailed in <<oauth2-client-properties, OAuth client properties>>.
  169. ====
  170. [[facebook-login-run-sample]]
  171. === Running the sample
  172. Launch the Spring Boot application by running *_sample.OAuth2LoginApplication_*.
  173. After the application successfully starts up, go to http://localhost:8080. You'll then be redirected to http://localhost:8080/login, which will display an _auto-generated login page_ with an anchor link for *Facebook*.
  174. Click through on the Facebook link and you'll be redirected to Facebook for authentication.
  175. After you authenticate using your Facebook credentials, the next page presented to you will be *Authorize application*.
  176. This page will ask you to *Authorize* the application you created in the previous step <<facebook-login-register-application, Add a New App>>.
  177. Click *_Authorize application_* to allow the OAuth application to access your _public profile_ and _email address_.
  178. At this point, the OAuth application will retrieve your personal user information from the *UserInfo Endpoint* and establish an _authenticated session_.
  179. The home page will then be displayed showing the user attributes retrieved from the UserInfo Endpoint, for example, id, name, etc.
  180. [[okta-login]]
  181. == Setting up *_Login with Okta_*
  182. The goal for this section of the guide is to setup login using Okta as the _Authentication Provider_.
  183. NOTE: http://developer.okta.com/docs/api/resources/oidc.html[Okta's OAuth 2.0 implementation] for authentication conforms to the
  184. http://openid.net/connect/[OpenID Connect] specification and is http://openid.net/certification/[OpenID Certified].
  185. In order to use Okta's OAuth 2.0 authentication system for login, you must first https://www.okta.com/developer/signup[create a developer account].
  186. [[okta-login-register-application]]
  187. === Add Application
  188. Sign in to your account _sub-domain_ and navigate to *_Applications -> Applications_* and then click on the _"Add Application"_ button.
  189. From the _"Add Application"_ page, click on the _"Create New App"_ button and enter the following:
  190. * *Platform:* Web
  191. * *Sign on method:* OpenID Connect
  192. Click on the _"Create"_ button.
  193. On the _"General Settings"_ page, enter the Application Name (for example, _"Spring Security Okta Login"_) and then click on the _"Next"_ button.
  194. On the _"Configure OpenID Connect"_ page, enter *http://localhost:8080/oauth2/authorize/code/okta* for the field *Redirect URIs* and then click _"Finish"_.
  195. NOTE: The *Redirect URI* is the path in the sample application that the end-user's user-agent is redirected back to after they have authenticated with Okta
  196. and have granted access to the application on the *Authorize application* page.
  197. TIP: The default redirect URI is *_"{scheme}://{serverName}:{serverPort}/oauth2/authorize/code/{registrationId}"_*.
  198. See <<oauth2-client-properties, OAuth client properties>> for more details on this default.
  199. The next page presented displays the _"General"_ tab selected for the application.
  200. The _"General"_ tab displays the _"Settings"_ and _"Client Credentials"_ used by the application.
  201. In the next step, we will _assign_ the application to _people_ in order to grant user(s) access to the application.
  202. [[okta-login-assign-application-people]]
  203. === Assign Application to People
  204. From the _"General"_ tab of the application, select the _"Assignments"_ tab and then click the _"Assign"_ button.
  205. Select _"Assign to People"_ and assign your account to the application. Then click the _"Save and Go Back"_ button.
  206. [[okta-login-configure-application-yml]]
  207. === Configuring application.yml
  208. Now that we have created a new application with Okta, we need to configure the sample application (client) for the _authentication flow_.
  209. Go to *_src/main/resources_* and edit *application.yml*. Add the following configuration:
  210. [source,yaml]
  211. ----
  212. security:
  213. oauth2:
  214. client:
  215. okta:
  216. client-id: ${client-id}
  217. client-secret: ${client-secret}
  218. authorization-uri: https://${account-subdomain}.oktapreview.com/oauth2/v1/authorize
  219. token-uri: https://${account-subdomain}.oktapreview.com/oauth2/v1/token
  220. user-info-uri: https://${account-subdomain}.oktapreview.com/oauth2/v1/userinfo
  221. jwk-set-uri: https://${account-subdomain}.oktapreview.com/oauth2/v1/keys
  222. ----
  223. Replace *${client-id}* and *${client-secret}* with the *client credentials* created in the previous section <<okta-login-register-application, Add Application>>.
  224. As well, replace *${account-subdomain}* in _authorization-uri_, _token-uri_, _user-info-uri_ and _jwk-set-uri_ with the *sub-domain* assigned to your account during the registration process.
  225. [TIP]
  226. .OAuth client properties
  227. ====
  228. . *security.oauth2.client* is the *_base property prefix_* for OAuth client properties.
  229. . Just below the *_base property prefix_* is the *_client property key_*, for example *security.oauth2.client.registrations.okta*.
  230. . At the base of the *_client property key_* are the properties for specifying the configuration for an OAuth Client.
  231. A list of these properties are detailed in <<oauth2-client-properties, OAuth client properties>>.
  232. ====
  233. [[okta-login-run-sample]]
  234. === Running the sample
  235. Launch the Spring Boot application by running *_sample.OAuth2LoginApplication_*.
  236. After the application successfully starts up, go to http://localhost:8080. You'll then be redirected to http://localhost:8080/login, which will display an _auto-generated login page_ with an anchor link for *Okta*.
  237. Click through on the Okta link and you'll be redirected to Okta for authentication.
  238. After you authenticate using your Okta credentials, the OAuth Client (application) will retrieve your email address and basic profile information from the http://openid.net/specs/openid-connect-core-1_0.html#UserInfo[*UserInfo Endpoint*]
  239. and establish an _authenticated session_. The home page will then be displayed showing the user attributes retrieved from the UserInfo Endpoint, for example, name, email, profile, sub, etc.
  240. [[user-authority-mapping]]
  241. == Mapping User Authorities
  242. After the user successfully authenticates with the _OAuth 2.0 Provider_, the `OAuth2User.getAuthorities()` may be re-mapped to a new set of `GrantedAuthority`(s), which is then supplied to the `OAuth2AuthenticationToken`.
  243. The `GrantedAuthority`(s) associated to the `OAuth2AuthenticationToken` is then used for authorizing requests, such as, `hasRole('USER') or hasRole('ADMIN')`.
  244. In order to implement custom user authority mapping, you need to provide an implementation of `GrantedAuthoritiesMapper` and configure it using `OAuth2LoginConfigurer`.
  245. The following is a partial implementation of `GrantedAuthoritiesMapper` that maps an `OidcUserAuthority` or `OAuth2UserAuthority` to a set of `GrantedAuthority`(s):
  246. [source,java]
  247. ----
  248. public class CustomGrantedAuthoritiesMapper implements GrantedAuthoritiesMapper {
  249. @Override
  250. public Collection<? extends GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities) {
  251. Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
  252. for (GrantedAuthority authority : authorities) {
  253. if (OidcUserAuthority.class.isInstance(authority)) {
  254. OidcUserAuthority userAuthority = (OidcUserAuthority)authority;
  255. IdToken idToken = userAuthority.getIdToken();
  256. UserInfo userInfo = userAuthority.getUserInfo();
  257. // TODO
  258. // Map the claims found in IdToken and/or UserInfo
  259. // to one or more GrantedAuthority's and add to mappedAuthorities
  260. } else if (OAuth2UserAuthority.class.isInstance(authority)) {
  261. OAuth2UserAuthority userAuthority = (OAuth2UserAuthority)authority;
  262. Map<String, Object> userAttributes = userAuthority.getAttributes();
  263. // TODO
  264. // Map the attributes found in userAttributes
  265. // to one or more GrantedAuthority's and add to mappedAuthorities
  266. }
  267. }
  268. return mappedAuthorities;
  269. }
  270. }
  271. ----
  272. The following _security configuration_ configures a custom `GrantedAuthoritiesMapper` for OAuth 2.0 Login:
  273. [source,java]
  274. ----
  275. @EnableWebSecurity
  276. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  277. @Override
  278. protected void configure(HttpSecurity http) throws Exception {
  279. http
  280. .authorizeRequests()
  281. .anyRequest().authenticated()
  282. .and()
  283. .oauth2Login()
  284. .userAuthoritiesMapper(new CustomGrantedAuthoritiesMapper());
  285. }
  286. }
  287. ----
  288. [[oauth2-login-auto-configuration]]
  289. == OAuth 2.0 Login auto-configuration
  290. As you worked through this guide and setup OAuth 2.0 Login with one of the Providers,
  291. we hope you noticed the ease in configuration and setup required in getting the sample up and running?
  292. And you may be asking, how does this all work? Thanks to some Spring Boot auto-configuration _magic_,
  293. we were able to automatically register the OAuth Client(s) configured in the `Environment`,
  294. as well, provide a minimal security configuration for OAuth 2.0 Login.
  295. The following provides an overview of the Spring Boot auto-configuration classes:
  296. [[client-registration-auto-configuration-class]]
  297. *_org.springframework.boot.autoconfigure.security.oauth2.client.ClientRegistrationAutoConfiguration_*::
  298. `ClientRegistrationAutoConfiguration` is responsible for registering a `ClientRegistrationRepository` _bean_ with the `ApplicationContext`.
  299. The `ClientRegistrationRepository` is composed of one or more `ClientRegistration` instances, which are created from the OAuth client properties
  300. configured in the `Environment` that are prefixed with `security.oauth2.client.registrations.[registration-id]`, for example, `security.oauth2.client.registrations.google`.
  301. NOTE: `ClientRegistrationAutoConfiguration` also loads a _resource_ named *oauth2-clients-defaults.yml*,
  302. which provides a set of default client property values for a number of _well-known_ Providers.
  303. More on this in the later section <<oauth2-default-client-properties, Default client property values>>.
  304. [[oauth2-login-auto-configuration-class]]
  305. *_org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2LoginAutoConfiguration_*::
  306. `OAuth2LoginAutoConfiguration` is responsible for enabling OAuth 2.0 Login,
  307. only if there is a `ClientRegistrationRepository` _bean_ available in the `ApplicationContext`.
  308. WARNING: The auto-configuration classes (and dependent resources) will eventually _live_ in the *Spring Boot Security Starter*.
  309. [[oauth2-client-properties]]
  310. === OAuth client properties
  311. The following specifies the common set of properties available for configuring an OAuth Client.
  312. [TIP]
  313. ====
  314. - *security.oauth2.client* is the *_base property prefix_* for OAuth client properties.
  315. - Just below the *_base property prefix_* is the *_client property key_*, for example *security.oauth2.client.registrations.google*.
  316. - At the base of the *_client property key_* are the properties for specifying the configuration for an OAuth Client.
  317. ====
  318. - *client-authentication-method* - the method used to authenticate the _Client_ with the _Provider_. Supported values are *basic* and *post*.
  319. - *authorized-grant-type* - the OAuth 2.0 Authorization Framework defines the https://tools.ietf.org/html/rfc6749#section-1.3.1[Authorization Code] grant type,
  320. which is used to realize the _"authentication flow"_. Currently, this is the only supported grant type.
  321. - *redirect-uri* - this is the client's _registered_ redirect URI that the _Authorization Server_ redirects the end-user's user-agent
  322. to after the end-user has authenticated and authorized access for the client.
  323. NOTE: The default redirect URI is _"{scheme}://{serverName}:{serverPort}/oauth2/authorize/code/{registrationId}"_, which leverages *URI template variables*.
  324. - *scope* - a comma-delimited string of scope(s) requested during the _Authorization Request_ flow, for example: _openid, email, profile_
  325. NOTE: _OpenID Connect Core 1.0_ defines these http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims[standard scope]: _profile, email, address, phone_
  326. NOTE: Non-standard scope may be defined by a standard _OAuth 2.0 Provider_. Please consult the Provider's OAuth API documentation to learn which scope are supported.
  327. - *authorization-uri* - the URI used by the client to redirect the end-user's user-agent to the _Authorization Server_ in order to obtain authorization from the end-user (the _Resource Owner_).
  328. - *token-uri* - the URI used by the client when exchanging an _Authorization Grant_ (for example, Authorization Code) for an _Access Token_ at the _Authorization Server_.
  329. - *user-info-uri* - the URI used by the client to access the protected resource *UserInfo Endpoint*, in order to obtain attributes of the end-user.
  330. - *jwk-set-uri* - the URI used to retrieve the https://tools.ietf.org/html/rfc7517[JSON Web Key (JWK)] `Set`,
  331. which contains cryptographic key(s) that are used to verify the https://tools.ietf.org/html/rfc7515[JSON Web Signature (JWS)] of the *ID Token* and optionally the *UserInfo Endpoint* response.
  332. - *user-name-attribute-name* - the name of the attribute returned in the *UserInfo Endpoint* response that references the *Name* of the end-user.
  333. NOTE: _OpenID Connect Core 1.0_ defines the http://openid.net/specs/openid-connect-core-1_0.html#StandardClaims[_name_ Claim], which is the end-user's full name and is the default used for `DefaultOidcUser`.
  334. IMPORTANT: Standard _OAuth 2.0 Provider's_ may vary the naming of their *Name* attribute. Please consult the Provider's *UserInfo* API documentation.
  335. This is a *_required_* property for `DefaultOAuth2User`.
  336. - *client-name* - this is a descriptive name used for the client. The name may be used in certain scenarios, for example, when displaying the name of the client in the _auto-generated login page_.
  337. - *registration-id* - an _id_ which uniquely identifies the client registration. It *must be* unique within a `ClientRegistrationRepository`.
  338. [[oauth2-default-client-properties]]
  339. === Default client property values
  340. As noted previously, <<client-registration-auto-configuration-class, `ClientRegistrationAutoConfiguration`>> loads a _resource_ named *oauth2-clients-defaults.yml*,
  341. which provides a set of default client property values for a number of _well-known_ Providers.
  342. For example, the *authorization-uri*, *token-uri*, *user-info-uri* rarely change for a Provider and therefore it makes sense to
  343. provide a set of defaults in order to reduce the configuration required by the user.
  344. Below are the current set of default client property values:
  345. .oauth2-clients-defaults.yml
  346. [source,yaml]
  347. ----
  348. security:
  349. oauth2:
  350. client:
  351. google:
  352. client-authentication-method: basic
  353. authorized-grant-type: authorization_code
  354. redirect-uri: "{scheme}://{serverName}:{serverPort}{baseAuthorizeUri}/{registrationId}"
  355. scope: openid, email, profile
  356. authorization-uri: "https://accounts.google.com/o/oauth2/auth"
  357. token-uri: "https://accounts.google.com/o/oauth2/token"
  358. user-info-uri: "https://www.googleapis.com/oauth2/v3/userinfo"
  359. jwk-set-uri: https://www.googleapis.com/oauth2/v3/certs
  360. client-name: Google
  361. github:
  362. client-authentication-method: basic
  363. authorized-grant-type: authorization_code
  364. redirect-uri: "{scheme}://{serverName}:{serverPort}{baseAuthorizeUri}/{registrationId}"
  365. scope: user
  366. authorization-uri: "https://github.com/login/oauth/authorize"
  367. token-uri: "https://github.com/login/oauth/access_token"
  368. user-info-uri: "https://api.github.com/user"
  369. client-name: GitHub
  370. facebook:
  371. client-authentication-method: post
  372. authorized-grant-type: authorization_code
  373. redirect-uri: "{scheme}://{serverName}:{serverPort}{baseAuthorizeUri}/{registrationId}"
  374. scope: public_profile, email
  375. authorization-uri: "https://www.facebook.com/v2.8/dialog/oauth"
  376. token-uri: "https://graph.facebook.com/v2.8/oauth/access_token"
  377. user-info-uri: "https://graph.facebook.com/me"
  378. client-name: Facebook
  379. okta:
  380. client-authentication-method: basic
  381. authorized-grant-type: authorization_code
  382. redirect-uri: "{scheme}://{serverName}:{serverPort}{baseAuthorizeUri}/{registrationId}"
  383. scope: openid, email, profile
  384. client-name: Okta
  385. ----
  386. = Appendix
  387. '''
  388. [[configure-non-spring-boot-app]]
  389. == Configuring a _Non-Spring-Boot_ application
  390. If you are not using Spring Boot for your application, you will not be able to leverage the auto-configuration features for OAuth 2.0 Login.
  391. You will be required to provide your own _security configuration_ in order to enable OAuth 2.0 Login.
  392. The following sample code demonstrates a minimal security configuration for enabling OAuth 2.0 Login.
  393. Let's assume we have a _properties file_ named *oauth2-clients.properties* on the _classpath_ and it specifies all the _required_ properties for an OAuth Client, specifically _Google_.
  394. .oauth2-clients.properties
  395. [source,properties]
  396. ----
  397. security.oauth2.client.registrations.google.client-id=${client-id}
  398. security.oauth2.client.registrations.google.client-secret=${client-secret}
  399. security.oauth2.client.registrations.google.client-authentication-method=basic
  400. security.oauth2.client.registrations.google.authorized-grant-type=authorization_code
  401. security.oauth2.client.registrations.google.redirect-uri=http://localhost:8080/oauth2/authorize/code/google
  402. security.oauth2.client.registrations.google.scope=openid,email,profile
  403. security.oauth2.client.registrations.google.authorization-uri=https://accounts.google.com/o/oauth2/auth
  404. security.oauth2.client.registrations.google.token-uri=https://accounts.google.com/o/oauth2/token
  405. security.oauth2.client.registrations.google.user-info-uri=https://www.googleapis.com/oauth2/v3/userinfo
  406. security.oauth2.client.registrations.google.jwk-set-uri=https://www.googleapis.com/oauth2/v3/certs
  407. security.oauth2.client.registrations.google.client-name=Google
  408. ----
  409. The following _security configuration_ will enable OAuth 2.0 Login using _Google_ as the _Authentication Provider_:
  410. [source,java]
  411. ----
  412. @EnableWebSecurity
  413. @PropertySource("classpath:oauth2-clients.properties")
  414. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  415. private Environment environment;
  416. public SecurityConfig(Environment environment) {
  417. this.environment = environment;
  418. }
  419. @Override
  420. protected void configure(HttpSecurity http) throws Exception {
  421. http
  422. .authorizeRequests()
  423. .anyRequest().authenticated()
  424. .and()
  425. .oauth2Login()
  426. .clients(clientRegistrationRepository());
  427. }
  428. @Bean
  429. public ClientRegistrationRepository clientRegistrationRepository() {
  430. List<ClientRegistration> clientRegistrations = Collections.singletonList(
  431. clientRegistration("security.oauth2.client.registrations.google."));
  432. return new InMemoryClientRegistrationRepository(clientRegistrations);
  433. }
  434. private ClientRegistration clientRegistration(String clientPropertyKey) {
  435. String registrationId = this.environment.getProperty(clientPropertyKey + "registration-id");
  436. String clientId = this.environment.getProperty(clientPropertyKey + "client-id");
  437. String clientSecret = this.environment.getProperty(clientPropertyKey + "client-secret");
  438. ClientAuthenticationMethod clientAuthenticationMethod = new ClientAuthenticationMethod(
  439. this.environment.getProperty(clientPropertyKey + "client-authentication-method"));
  440. AuthorizationGrantType authorizationGrantType = AuthorizationGrantType.valueOf(
  441. this.environment.getProperty(clientPropertyKey + "authorized-grant-type").toUpperCase());
  442. String redirectUri = this.environment.getProperty(clientPropertyKey + "redirect-uri");
  443. String[] scope = this.environment.getProperty(clientPropertyKey + "scope").split(",");
  444. String authorizationUri = this.environment.getProperty(clientPropertyKey + "authorization-uri");
  445. String tokenUri = this.environment.getProperty(clientPropertyKey + "token-uri");
  446. String userInfoUri = this.environment.getProperty(clientPropertyKey + "user-info-uri");
  447. String jwkSetUri = this.environment.getProperty(clientPropertyKey + "jwk-set-uri");
  448. String clientName = this.environment.getProperty(clientPropertyKey + "client-name");
  449. return new ClientRegistration.Builder(registrationId)
  450. .clientId(clientId)
  451. .clientSecret(clientSecret)
  452. .clientAuthenticationMethod(clientAuthenticationMethod)
  453. .authorizedGrantType(authorizationGrantType)
  454. .redirectUri(redirectUri)
  455. .scope(scope)
  456. .authorizationUri(authorizationUri)
  457. .tokenUri(tokenUri)
  458. .userInfoUri(userInfoUri)
  459. .jwkSetUri(jwkSetUri)
  460. .clientName(clientName)
  461. .build();
  462. }
  463. }
  464. ----