Understanding OAuth 2.0: Roles, Grant Types, and Spring Security OAuth2 Client Implementation

This article explains the OAuth 2.0 authorization framework, describes its four core roles and various grant types, and demonstrates how to configure a Spring Security OAuth2 client for GitHub login, including endpoint details, request parameters, and code examples.

Architecture Digest
Architecture Digest
Architecture Digest
Understanding OAuth 2.0: Roles, Grant Types, and Spring Security OAuth2 Client Implementation

OAuth 2.0 is an authorization protocol that allows third‑party applications to access protected HTTP resources, such as logging in with GitHub or Google accounts. The diagram below shows the GitHub login flow for the Coding platform.

The article introduces key OAuth 2.0 concepts—roles, grant types, and endpoints—using a mind map to help readers understand the protocol.

In addition to the protocol, the article shows how to combine OAuth 2.0 with Spring Security OAuth2 to build an OAuth2 client, applying the knowledge to a real project.

OAuth 2.0 Roles

Four roles exist in OAuth 2.0:

Resource Owner
Authorization Server
Client
Resource Server
OAuth 2.0 high‑level authorization flow

Resource Owner

The Resource Owner is the end user. In the GitHub‑to‑Coding example, the user authorizes Coding to read their GitHub profile, email, etc.

Resource Server

The Resource Server stores the protected resources; in the example it is the GitHub server that holds the user’s data.

Client

The Client is the application that wants to access the resources, e.g., Coding, which initiates the authorization request and later obtains an access token.

Authorization Server

The Authorization Server authenticates the Resource Owner and issues the authorization code or access token. In the example, GitHub’s server plays this role.

Summary of Roles

Resource Owner: GitHub user

Authorization Server: GitHub server

Client: Coding system

Resource Server: GitHub server

Both the Authorization Server and Resource Server can be deployed independently in micro‑service architectures.

OAuth2 Endpoints

OAuth2 defines three important endpoints:

Authorization Endpoint – used by the client to obtain the Resource Owner’s consent.

Token Endpoint – used by the client to exchange the authorization code for an access token.

Redirect (optional) Endpoint – used by the Authorization Server to send the response back to the client.

Grant Types

Four grant types are defined:

Authorization Code Grant

Client Credentials Grant

Resource Owner Password Credentials Grant

Implicit Grant

Authorization Code Grant

This is the most common flow (e.g., GitHub login). The client receives an authorization code from the Authorization Server, then exchanges it for an access token.

Step‑by‑step example:

A.1 User visits https://coding.net/login and clicks the GitHub login button.

A.2 Coding redirects the browser to GitHub’s authorization URL with client_id and redirect_uri parameters.

B.1 User logs into GitHub.

B.2 User clicks the “Authorize” button.

C.1 GitHub returns an authorization code to the redirect URI.

D Coding exchanges the code for an access token via GitHub’s token endpoint.

Key parameters: client_id: the app’s identifier registered on GitHub. redirect_uri: the callback URL where GitHub sends the code. code: temporary credential used to obtain the access token. state: optional value to prevent CSRF attacks.

Authorization Code Request Example

GET https://github.com/login/oauth/authorize?client_id=YOUR_CLIENT_ID&scope=user:email&redirect_uri=https://coding.net/api/oauth/github/callback&response_type=code

Authorization Code Response Example

GET https://coding.net/api/oauth/github/callback?code=AUTH_CODE&state=xyz

Client Credentials Grant

Used for service‑to‑service communication. The client directly requests an access token from the token endpoint using its client_id and client_secret.

Client Credentials Request

POST /oauth/token HTTP/1.1
Authorization: Basic BASE64(client_id:client_secret)
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials

Response

{
  "access_token":"2YotnFZFEjr1zCsicMWpAA",
  "token_type":"example",
  "expires_in":3600,
  "example_parameter":"example_value"
}

Resource Owner Password Credentials Grant

The client collects the user’s username and password and sends them to the token endpoint together with its own credentials.

Request Example

POST /oauth/token HTTP/1.1
Authorization: Basic BASE64(client_id:client_secret)
Content-Type: application/x-www-form-urlencoded

grant_type=password&username=USER&password=PASS

Response Example

{
  "access_token":"2YotnFZFEjr1zCsicMWpAA",
  "token_type":"example",
  "expires_in":3600,
  "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
  "example_parameter":"example_value"
}

Implicit Grant

The client receives the access token directly from the Authorization Endpoint as a URL fragment, without a separate token request.

Implicit Grant Request Parameters

GET https://github.com/login/oauth/authorize?client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&response_type=token&scope=read:user

Response (fragment)

http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=example&expires_in=3600

OAuth2 Client with Spring Security

To implement a GitHub login client, first register an OAuth App on GitHub and note the clientId and clientSecret. The Authorization callback URL corresponds to the redirect_uri used by Spring Security.

Dependency Configuration

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Spring Security OAuth2 already provides built‑in configurations for common providers (GitHub, Google, Facebook, Okta). You only need to supply clientId and clientSecret for the chosen provider.

Registration POJO Example

public static class Registration {
    // Authorization server provider name
    private String provider;
    // Client ID
    private String clientId;
    // Client secret
    private String clientSecret;
    // ... other fields
}

Application Properties

spring.security.oauth2.client.registration.github.clientId=5f...efca2daccf85bede32
spring.security.oauth2.client.registration.github.clientSecret=01d...e67f99dde864fb6524

Redirect URI Template

Spring Security uses the template {baseUrl}/login/oauth2/code/{registrationId}. For GitHub, the final redirect URI becomes {baseUrl}/login/oauth2/code/github.

Running the Application

After configuring the client and redirect URI, start the Spring Boot server and open http://localhost:8080/. The first request will be redirected to GitHub’s authorization endpoint.

CommonOAuth2Provider Enum (Source Snippet)

public enum CommonOAuth2Provider {
    GOOGLE { ... }
    GITHUB { ... }
    FACEBOOK { ... }
    OKTA { ... }
    // default redirect URL template
    private static final String DEFAULT_REDIRECT_URL = "{baseUrl}/{action}/oauth2/code/{registrationId}";
}

OAuth2LoginAuthenticationFilter

This filter processes the authorization response, extracts the code, builds an OAuth2LoginAuthenticationToken, and delegates to the AuthenticationManager to obtain the access token.

public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
    // ... extract parameters, validate, retrieve ClientRegistration
    OAuth2LoginAuthenticationToken authenticationRequest = new OAuth2LoginAuthenticationToken(
        clientRegistration,
        new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
    // authenticate and obtain token
    OAuth2LoginAuthenticationToken authenticationResult =
        (OAuth2LoginAuthenticationToken) this.getAuthenticationManager().authenticate(authenticationRequest);
    return oauth2Authentication;
}

OAuth2LoginAuthenticationProvider

The provider uses an OAuth2AccessTokenResponseClient to call the token endpoint and retrieve the access token.

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OAuth2LoginAuthenticationToken auth = (OAuth2LoginAuthenticationToken) authentication;
    OAuth2AccessTokenResponse tokenResponse = this.accessTokenResponseClient.getTokenResponse(
        new OAuth2AuthorizationCodeGrantRequest(auth.getClientRegistration(), auth.getAuthorizationExchange()));
    // ... build authenticated principal
    return authenticationResult;
}

References

OAuth 2.0 Developers Guide

draft-ietf-oauth-v2

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendOAuth2Authorizationspring-securityaccess_tokenGrant Types
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.