OpenID Connect for APIs — Complete Authentication Guide
In this tutorial, you will learn about Openid Connect for APIs. We cover key concepts, practical examples, and best practices to help you master this topic.
OpenID Connect (OIDC) is an identity layer built on top of OAuth 2.0. While OAuth 2.0 handles authorization (what you can access), OIDC adds authentication (who you are) through ID tokens and the UserInfo endpoint.
What You'll Learn
You'll learn how OpenID Connect adds authentication to OAuth 2.0, ID token structure, and how to verify user identity in your API.
Why It Matters
OAuth 2.0 alone cannot tell you who the user is. OIDC provides a standard way to authenticate users, eliminating custom login systems and enabling single sign-on across applications.
Real-World Use
An enterprise dashboard uses OIDC with Azure Active Directory. Employees log in once and access the dashboard, HR system, and project management tools without separate credentials.
sequenceDiagram
participant User
participant App as Client App
participant OP as OpenID Provider
participant API as Resource Server
User->>App: Click "Sign In"
App->>OP: Authentication Request (scope=openid)
OP->>User: Authenticate
User->>OP: Credentials
OP->>App: ID Token + Access Token
App->>OP: Validate ID Token (JWKS)
OP-->>App: Token Valid
App->>API: API Request (Access Token)
API->>App: Response Data
App->>User: Display User Info
Teacher's Mindset
If OAuth 2.0 is a key card that opens doors, OIDC is the same key card that also shows your name and photo. It proves both your identity and your permissions.
Implementing OpenID Connect
from flask import Flask, request, jsonify
from authlib.integrations.flask_client import OAuth
import jwt
app = Flask(__name__)
oauth = OAuth(app)
oauth.register(
name="google",
client_id="your-client-id",
client_secret="your-client-secret",
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
client_kwargs={"scope": "openid profile email"}
)
@app.route("/login")
def login():
redirect_uri = "https://app.example.com/authorize"
return oauth.google.authorize_redirect(redirect_uri)
@app.route("/authorize")
def authorize():
token = oauth.google.authorize_access_token()
userinfo = oauth.google.parse_id_token(token)
return jsonify({
"sub": userinfo["sub"],
"email": userinfo["email"],
"name": userinfo["name"]
})
# ID token validation
def validate_id_token(id_token, jwks_uri, client_id):
jwks = requests.get(jwks_uri).json()
jwk_set = PyJWKSet(jwks)
header = jwt.get_unverified_header(id_token)
signing_key = jwk_set[header["kid"]]
claims = jwt.decode(
id_token,
signing_key.key,
algorithms=["RS256"],
audience=client_id,
issuer="https://accounts.google.com",
options={
"require": ["iss", "sub", "aud", "exp", "iat"]
}
)
return claims
# Using userinfo endpoint
def get_user_info(access_token):
response = requests.get(
"https://op.example.com/userinfo",
headers={"Authorization": f"Bearer {access_token}"}
)
if response.status_code == 200:
return response.json()
raise ValueError("Failed to get user info")
Common Mistakes
| Mistake | Why It's Wrong | Fix |
|---|---|---|
| Not validating the ID token signature | Anyone can forge identity claims | Verify signature using provider's JWKS |
| Missing nonce check | Replay attacks possible | Include and validate nonce in ID token |
| Using access token for identity | Access token is for authorization, not identity | Use ID token for user info, access token for API calls |
| Not checking issuer | Tokens from any provider accepted | Verify iss claim matches expected provider |
| Trusting userinfo without validating token | Userinfo endpoint could be spoofed | Always validate access token before calling userinfo |
Practice Questions
- What does the "openid" scope request?
- What is the difference between an ID token and an access token in OIDC?
- What claims are required in an ID token?
- How does OIDC enable single sign-on?
- What is the UserInfo endpoint?
Challenge
Implement OIDC login with Google. Validate the ID token manually using JWKS. Extract user profile information and create a local user session.
FAQ
Mini Project
Deploy Keycloak as your OpenID Provider. Register a client app and implement OIDC login with ID token validation. Test with expired and invalid tokens.
What's Next
Learn about API keys as a simple authentication method for machine-to-machine communication.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro