OAuth 2.0 Login of Spring Security 5.1

Keywords: Google Spring github Attribute

1.OAuth 2.0 Login

The OAuth 2.0 login function provides applications with the ability to login to applications using existing accounts on OAuth 2.0 providers (such as GitHub) or OpenID Connect 1.0 providers (such as Google). OAuth 2.0 Login implements use cases: "Log in with Google" or "Log in with GitHub".

OAuth 2.0 login is implemented using authorization code grant, such as OAuth
2.0 Authorization Framework
and OpenID Connect Core 1.0 As specified in.

1.1 Spring Boot 2.x Sample

Spring Boot 2.x brings complete automatic configuration for OAuth 2.0 login.

This section describes how to configure the OAuth 2.0 login example using Google as an authentication provider, and introduces the following topics:

  • 1.1.1 Initial Installation
  • 1.1.2 Setting Redirected URI
  • 1.1.3 Configure application.yml
  • 1.1.4 Start application

1.1.1 Initial Installation

To log in using Google's OAuth 2.0 authentication system, you must set up a project in the Google API console to obtain the OAuth 2.0 credentials.

Google's OAuth 2.0 Authentication Implementation accord with OpenID
Connect1.0
Specification and adoption OpenID authentication

according to OpenID Connect The instructions on the page begin with the section "Setting up OAuth 2.0".

After completing the "Get the OAuth 2.0 credentials" instructions, you should have a new OAuth client, whose credentials contain the client ID and client key.

1.1.2 Setting Redirected URI

The redirect URI is the path in the application, and the user agent of the end user redirects the path back after authenticating through Google and granting access to the OAuth client (created in the previous step) on the "Agree" page.

In the Set Redirected URI sub-section, make sure that the Authorized Redirected URI field is set to

http://localhost:8080/login/oauth2/code/google

The default redirection URI template is {baseUrl}/login/oauth2/code/{registrationId}.
RegistratinId is the unique identifier of Client Registration.

1.1.3 Configure application.yml

Now that you have a new OAuth client and Google, you need to configure the application to use the OAuth client for the authentication process

1. Go to application.yml and set the following configuration

spring:
  security:
    oauth2:
      client:
        registration:   1
          google:   2
            client-id: google-client-id
            client-secret: google-client-secret

Example 6.1. OAuth Client properties

Example 6.1 OAuth client properties

  • 1 spring.security.oauth2.client.registration is the basic attribute prefix of OAuth client attributes.
  • 2 The basic attribute prefix is followed by the ID of ClientRegistration, such as google.

1.1.4 Start application

Start the Spring Boot 2.x example and go to http://localhost:8080. Then you will be redirected to the default auto-generated login page that displays a link to Google.

Click on the Google link and you will redirect to Google for authentication.

After authenticating with your Google account credentials, the next page displayed to you is the "Agree" screen. The "Agree" screen asks you to allow or deny access to the OAuth client you created earlier. Click Allow to authorize the OAuth client to access your e-mail address and basic profile information.

At this point, the OAuth client retrieves your e-mail address and basic configuration file information from the UserInfo endpoint and establishes an authenticated session.

1.2 Spring Boot 2.x Property Mappings

The following table outlines the mapping of Spring Boot 2.x OAuth client attributes to ClientRegistration attributes:

Spring Boot 2.x ClientRegistration
spring.security.oauth2.client.registration.[registrationId] registrationId
spring.security.oauth2.client.registration.[registrationId].client-id clientId
spring.security.oauth2.client.registration.[registrationId].client-secret clientSecret
spring.security.oauth2.client.registration.[registrationId].client-authentication-method clientAuthenticationMethod
spring.security.oauth2.client.registration.[registrationId].authorization-grant-type authorizationGrantType
spring.security.oauth2.client.registration.[registrationId].redirect-uri redirectUriTemplate
spring.security.oauth2.client.registration.[registrationId].scope scopes
spring.security.oauth2.client.registration.[registrationId].client-name clientName
spring.security.oauth2.client.provider.[providerId].authorization-uri providerDetails.authorizationUri
spring.security.oauth2.client.provider.[providerId].token-uri providerDetails.tokenUri
spring.security.oauth2.client.provider.[providerId].jwk-set-uri providerDetails.jwkSetUri
spring.security.oauth2.client.provider.[providerId].user-info-uri providerDetails.userInfoEndpoint.uri
spring.security.oauth2.client.provider.[providerId].user-info-authentication-method providerDetails.userInfoEndpoint.authenticationMethod
spring.security.oauth2.client.provider.[providerId].userNameAttribute providerDetails.userInfoEndpoint.userNameAttributeName

1.3 CommonOAuth2Provider

CommonOAuth2Provider predefines a set of default client properties for many well-known providers: Google, GitHub, Facebook and Okta.

For example, authorization-uri, token-uri and user-info-uri do not change providers frequently. Therefore, it makes sense to provide default values to reduce the required configuration.

As mentioned earlier, when we configure a Google client, we only need the client-id and client-secret attributes.

The following listing shows an example:

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: google-client-id
            client-secret: google-client-secret

The automatic default of client properties works seamlessly here because registrationId (google) matches the GOOGLE enumeration (case-insensitive) in Common OAuth2Provider.

In cases where you might want to specify other registrationId (such as google-login), you can still exploit the automatic default of client properties by configuring the provider property.

The following listing shows an example:

spring:
  security:
    oauth2:
      client:
        registration:
          google-login: 1
            provider: google    2
            client-id: google-client-id
            client-secret: google-client-secret
  • 1 registrationId is set to google-login.
  • The 2provider property is set to google, which will automatically default to the client property set in CommonOAuth2Provider.GOOGLE.getBuilder ().

1.4 Configuring Custom Provider Properties

Some OAuth 2.0 providers support multiple tenants, which results in each tenant (or subdomain) using different protocol endpoints.

For example, an OAuth client registered with Okta is assigned to a specific subdomain and has its own protocol endpoint.

In these cases, Spring Boot 2.x provides the following basic properties for configuring custom provider properties:

spring.security.oauth2.client.provider.[providerId]

The following listing shows an example:

spring:
  security:
    oauth2:
      client:
        registration:
          okta:
            client-id: okta-client-id
            client-secret: okta-client-secret
        provider:
          okta: 1
            authorization-uri: https://your-subdomain.oktapreview.com/oauth2/v1/authorize
            token-uri: https://your-subdomain.oktapreview.com/oauth2/v1/token
            user-info-uri: https://your-subdomain.oktapreview.com/oauth2/v1/userinfo
            user-name-attribute: sub
            jwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys
  • 1 Basic property (spring.security.oauth2.client.provider.okta) allows you to customize the configuration protocol endpoint location.

1.5 Overriding Spring Boot 2.x Auto-configuration

The Spring Boot 2.x automatic configuration class supported by the OAuth client is OAuth2ClientAutoConfiguration.

It performs the following tasks:

Register Client Registration Repository@Bean consisting of Client Registration from the configured OAuth client properties.
Provide WebSecurity ConfigurerAdapter@Configuration and enable OAuth 2.0 login through httpSecurity.oauth2Login().
If you need to override automatic configuration according to specific requirements, you can do this in the following ways:

  • Register Client Registration Repository@Bean
  • Provide Web Security Configurer Adapter
  • Full coverage automatic configuration

Register Client Registration Repository@Bean

The following example shows how to register Client Registration Repository@Bean:

@Configuration
public class OAuth2LoginConfig {

    @Bean
    public ClientRegistrationRepository clientRegistrationRepository() {
        return new InMemoryClientRegistrationRepository(this.googleClientRegistration());
    }

    private ClientRegistration googleClientRegistration() {
        return ClientRegistration.withRegistrationId("google")
            .clientId("google-client-id")
            .clientSecret("google-client-secret")
            .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}")
            .scope("openid", "profile", "email", "address", "phone")
            .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth")
            .tokenUri("https://www.googleapis.com/oauth2/v4/token")
            .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
            .userNameAttributeName(IdTokenClaimNames.SUB)
            .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
            .clientName("Google")
            .build();
    }
}

Provide Web Security Configurer Adapter

The following example illustrates how to use @Enable Web Security to provide Web Security Configurer Adapter and enable OAuth 2.0 login through httpSecurity.oauth2Login ():

@EnableWebSecurity
public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .oauth2Login();
    }
}

Full coverage automatic configuration

The following example shows how to fully override automatic configuration by registering Client Registration Repository@Bean and providing Web Security Configurer Adapter.

@Configuration
public class OAuth2LoginConfig {

    @EnableWebSecurity
    public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                .oauth2Login();
        }
    }

    @Bean
    public ClientRegistrationRepository clientRegistrationRepository() {
        return new InMemoryClientRegistrationRepository(this.googleClientRegistration());
    }

    private ClientRegistration googleClientRegistration() {
        return ClientRegistration.withRegistrationId("google")
            .clientId("google-client-id")
            .clientSecret("google-client-secret")
            .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}")
            .scope("openid", "profile", "email", "address", "phone")
            .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth")
            .tokenUri("https://www.googleapis.com/oauth2/v4/token")
            .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
            .userNameAttributeName(IdTokenClaimNames.SUB)
            .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
            .clientName("Google")
            .build();
    }
}

1.6 Java Configuration without Spring Boot 2.x

If you can't use Spring Boot 2.x and want to configure a predefined provider (for example, Google) in Common OAuth 2 Provider, apply the following configuration:

@Configuration
public class OAuth2LoginConfig {

    @EnableWebSecurity
    public static class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                .oauth2Login();
        }
    }

    @Bean
    public ClientRegistrationRepository clientRegistrationRepository() {
        return new InMemoryClientRegistrationRepository(this.googleClientRegistration());
    }

    @Bean
    public OAuth2AuthorizedClientService authorizedClientService(
            ClientRegistrationRepository clientRegistrationRepository) {
        return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
    }

    @Bean
    public OAuth2AuthorizedClientRepository authorizedClientRepository(
            OAuth2AuthorizedClientService authorizedClientService) {
        return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService);
    }

    private ClientRegistration googleClientRegistration() {
        return CommonOAuth2Provider.GOOGLE.getBuilder("google")
            .clientId("google-client-id")
            .clientSecret("google-client-secret")
            .build();
    }
}

1.7 Additional Resources

The following additional resources describe advanced configuration options:

  • OAuth 2.0 login page
  • Redirected endpoint
  • UserInfo endpoint:
    • Mapping user privileges
    • Configure custom OAuth2User
    • OAuth 2.0 UserService
    • OpenID Connect 1.0 UserService

Posted by Gayathri on Tue, 30 Apr 2019 23:00:39 -0700