3. Client

To make your web application into an OAuth2 client, you can add @EnableOAuth2Client and Spring Boot creates an OAuth2ClientContext and OAuth2ProtectedResourceDetails that are necessary to create an OAuth2RestOperations. Spring Boot does not automatically create such a bean, but you can easily create your own, as the following example shows:

@Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext,
        OAuth2ProtectedResourceDetails details) {
    return new OAuth2RestTemplate(details, oauth2ClientContext);
}
[Note]Note

You may want to add a qualifier and review your configuration, as more than one RestTemplate may be defined in your application.

This configuration uses security.oauth2.client.* as credentials (the same as you might be using in the Authorization Server). However, in addition, it needs to know the authorization and token URIs in the Authorization Server, as the following example shows:

application.yml. 

security:
  oauth2:
    client:
      clientId: bd1c0a783ccdd1c9b9e4
      clientSecret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1
      accessTokenUri: https://github.com/login/oauth/access_token
      userAuthorizationUri: https://github.com/login/oauth/authorize
      clientAuthenticationScheme: form

An application with this configuration redirects to Github for authorization when you attempt to use the OAuth2RestTemplate. If you are already signed into Github. you should not even notice that it has authenticated. These specific credentials work only if your application is running on port 8080 (you can register your own client application in Github or other provider for more flexibility).

To limit the scope that the client asks for when it obtains an access token, you can set security.oauth2.client.scope (comma separated or an array in YAML). By default, the scope is empty, and it is up to Authorization Server to decide what the defaults should be (usually depending on the settings in the client registration that it holds).

[Note]Note

There is also a setting for security.oauth2.client.client-authentication-scheme, which defaults to header (but you might need to set it to form if, like Github for instance, your OAuth2 provider does not like header authentication). In fact, the security.oauth2.client.* properties are bound to an instance of AuthorizationCodeResourceDetails, so all of its properties can be specified.

[Tip]Tip

In a non-web application, you can still create an OAuth2RestOperations, and it is still wired into the security.oauth2.client.* configuration. In this case, you are asking for is a “client credentials token grant” if you use it (and there is no need to use @EnableOAuth2Client or @EnableOAuth2Sso). To prevent that infrastructure being defined, remove the security.oauth2.client.client-id from your configuration (or make it be an empty string).