Skip to content
IRC-CodingIRC-Coding
OAuth2OpenID ConnectOIDCAccess TokenID TokenPKCE

OAuth2 and OpenID Connect for APIs

Master OAuth2 and OpenID Connect: flows, tokens, scopes, PKCE, and best practices for secure API authentication.

S

schutzgeist

6 min read
OAuth2 and OpenID Connect for APIs

OAuth2 and OpenID Connect for APIs

OAuth2 enables authorized access to APIs, while OpenID Connect layers on top a standardized way to authenticate users.

Overview

OAuth2 is a widely adopted authorization framework that lets applications access resources on behalf of a user without ever handling their password directly. OpenID Connect builds on top of this by adding an identity layer that confirms a user’s authentication through ID Tokens. Together, they form the foundation for modern Single Sign-On and API security. Key concepts include the Authorization Server, Resource Server, Client, Access Token, ID Token, Scopes, Refresh Token, and various flows such as Authorization Code Flow with PKCE. Getting the implementation right is crucial for preventing token theft, man-in-the-middle attacks, and unauthorized access. OAuth2 and OpenID Connect are now standard in virtually all modern web, mobile, and cloud applications.

Key Components

Authorization Server

The Authorization Server is the central authority that issues tokens. It authenticates the user, requests consent, and issues an Access Token, optionally an ID Token, and a Refresh Token. Well-known Authorization Servers include Keycloak, Auth0, Okta, and Azure AD.

Resource Server

The Resource Server is the API that hosts protected resources. It validates the Access Token and decides whether a request is allowed based on the scopes and claims within it. The Resource Server doesn’t know the user directly—it only knows what’s in the token.

Client

The Client is the application that wants to access the API on behalf of the user. Clients can be confidential, like a backend server, or public, like a mobile app or single-page application. Public clients need extra protection through mechanisms like PKCE.

Access Token

An Access Token is a short-lived token that grants the client permission to access protected resources. It’s sent in the Authorization header as a Bearer Token. Access Tokens should have the shortest reasonable lifetime and always be transmitted over HTTPS.

ID Token

The ID Token is issued by OpenID Connect and carries information about the user’s identity, such as sub, name, and email. It’s a JWT and is used for authentication, not API access. API access happens with the Access Token.

Refresh Token

Refresh Tokens are long-lived tokens that let a client request a new Access Token without asking the user for their password again. They must be carefully protected and should be revocable if compromised.

Scopes

Scopes define what permissions a client is requesting. Examples include read, write, or profile. Either the user or the Authorization Server decides which scopes are granted. The Resource Server then checks whether the requested action falls within the token’s scopes.

Authorization Code Flow

Authorization Code Flow is the most secure and widely used OAuth2 flow. The user is redirected to the Authorization Server, logs in, and the server returns a code to the client application. The client then exchanges this code for an Access Token and ID Token.

PKCE

PKCE stands for Proof Key for Code Exchange and extends the Authorization Code Flow. It protects public clients like mobile apps and single-page applications from code interception attacks. The client generates a random code verifier and sends a hash of it as the code challenge.

Client Credentials Flow

Client Credentials Flow is used for machine-to-machine communication when no user is involved. The client authenticates directly with the Authorization Server using its Client ID and Client Secret and receives an Access Token.

Implicit Flow and Password Flow

Implicit Flow and Resource Owner Password Credentials Flow are considered obsolete and should no longer be used due to security risks. Modern applications use Authorization Code Flow with PKCE instead.

Token Validation

The Resource Server must validate the Access Token before processing a request. This involves checking the signature, expiration time, issuer, audience, and scopes. Self-signed JWTs are verified with the Authorization Server’s public key, while opaque tokens are checked through introspection.

Logout and Session Management

OpenID Connect defines several logout mechanisms, including RP-Initiated Logout, Back-Channel Logout, and Front-Channel Logout. These allow sessions to be centrally terminated and tokens to be invalidated.

Practical Example

A mobile app wants to access a user profile API using Authorization Code Flow with PKCE.

Step 1: The app generates a code verifier and code challenge:

code_verifier = random_string(128)
code_challenge = BASE64URL(SHA256(code_verifier))

Step 2: The app redirects the user to the Authorization Server:

https://auth.example.com/authorize?
  response_type=code
  &client_id=mobile-app
  &redirect_uri=app://callback
  &scope=openid profile read:profile
  &code_challenge=abc123
  &code_challenge_method=S256
  &state=xyz789

Step 3: After successful login and consent, the app receives an authorization code:

app://callback?code=AUTH_CODE&state=xyz789

Step 4: The app exchanges the code for tokens:

POST /token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&code=AUTH_CODE
&redirect_uri=app://callback
&client_id=mobile-app
&code_verifier=CODE_VERIFIER

Step 5: The app calls the API:

GET /api/v1/profile
Authorization: Bearer ACCESS_TOKEN

PKCE keeps the flow secure for public clients because an intercepted code cannot be exchanged without the code verifier.

FAQ: OAuth2 and OpenID Connect

1. What is OAuth2?

OAuth2 is an authorization framework that enables applications to access resources on behalf of a user without knowing the user’s password.

2. What is OpenID Connect?

OpenID Connect is an identity layer built on OAuth2. It enables user authentication and provides an ID Token with identity information.

3. What is the difference between Access Token and ID Token?

The Access Token is used for accessing protected APIs. The ID Token is used for authentication and contains the user’s identity information.

4. What is PKCE?

PKCE stands for Proof Key for Code Exchange. It’s an extension to the Authorization Code Flow that protects public clients like mobile apps and single-page applications from code interception attacks.

5. What are Scopes?

Scopes define the permissions a client is requesting. They’re specified at the Authorization Server and included in the Access Token. The Resource Server checks them before granting access.

6. What is a Refresh Token?

A Refresh Token is a long-lived token that lets a client request a new Access Token without asking the user to log in again. Refresh Tokens must be carefully protected.

7. What is Authorization Code Flow?

Authorization Code Flow is the most common and secure OAuth2 flow. After the user logs in, the client receives a code and exchanges it for tokens in the backend.

8. What is Client Credentials Flow?

Client Credentials Flow is used for machine-to-machine communication. The client authenticates directly with its Client ID and Client Secret and receives an Access Token.

9. Why are Implicit and Password Flow considered obsolete?

Implicit and Password Flow carry security risks, such as token exposure in the browser or sharing passwords with third parties. Modern applications use Authorization Code Flow with PKCE.

10. What is Token Introspection?

Token Introspection is an endpoint on the Authorization Server that lets a Resource Server check an opaque token. The server returns information about validity, expiration, and scopes.

11. What is an Audience Claim?

The Audience Claim in a token specifies which API or service the token is intended for. The Resource Server checks whether it is the intended audience to prevent token misuse.

12. How is a JWT Access Token validated?

A JWT Access Token is checked for signature, issuer, audience, expiration time, and scopes. The signature is verified using the Authorization Server’s public key.

13. What is Single Sign-On?

Single Sign-On allows users to log in once and then access multiple applications without having to log in again. OpenID Connect is a common protocol for this.

14. What is Back-Channel Logout?

Back-Channel Logout is an OpenID Connect mechanism where the Authorization Server notifies applications directly via a server-to-server call that a session has ended.

15. What are common OAuth2 mistakes?

Common mistakes include long-lived Access Tokens, missing PKCE for public clients, skipping audience validation, unencrypted transmission, long-lived Refresh Tokens without revocation, and incorrectly using ID Tokens as Access Tokens.

Continue Your API Learning Path

The next article in the API learning path covers JWT Token: Structure, Security, and Best Practices — how JSON Web Tokens are structured, signature schemes, and security best practices.

References

  1. https://datatracker.ietf.org/doc/html/rfc6749
  2. https://openid.net/specs/openid-connect-core-1_0.html
  3. https://datatracker.ietf.org/doc/html/rfc7636

To deepen your understanding of OAuth2, OpenID Connect, and API security, we recommend these books:

IT CyberSecurity

Books about IT security, authentication, encryption and security best practices

The Web Application Hacker's Handbook von Dafydd Stuttard, Marcus Pinto

The Web Application Hacker's Handbook von Dafydd Stuttard, Marcus Pinto

Bei Amazon ansehen

Affiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.

Back to Blog
Share:

Related Posts