Learn

Navigate through learn topics

OAuth 2.0

Understanding OAuth 2.0 authentication and authorisation protocols for secure API access

Last updated: 8/15/2025

OAuth 2.0 is the industry standard protocol for authorisation that enables applications to access user data without exposing user credentials.

What is OAuth 2.0?

OAuth 2.0 is an authorisation framework that allows third-party applications to access user resources on behalf of the user without sharing their credentials.

Key concept: OAuth 2.0 is about authorisation, not authentication. It answers "What can this application do?" rather than "Who is this user?"

How OAuth 2.0 Works

The OAuth Flow

The OAuth 2.0 flow involves several parties working together to grant access:

  1. Resource Owner: The user who owns the data
  2. Client: The application requesting access
  3. Authorization Server: The server that authenticates the user and issues tokens
  4. Resource Server: The server hosting the protected resources

Basic Authorization Flow

User → Client → Authorization Server → User Consent → Authorization Code
Client → Authorization Server → Access Token → Resource Server → Data

OAuth 2.0 Grant Types

Authorization Code Flow

Most secure and recommended for web applications

This flow involves multiple steps and is designed for applications that can securely store a client secret.

Steps:

  1. User visits the client application
  2. Client redirects to authorization server
  3. User authenticates and consents
  4. Authorization server redirects back with code
  5. Client exchanges code for access token
  6. Client uses access token to access resources

Implicit Flow

Simpler but less secure

Directly returns an access token without an authorization code.

Use case: Single-page applications where storing a client secret is difficult.

Client Credentials Flow

For machine-to-machine communication

When the client is acting on its own behalf, not on behalf of a user.

Resource Owner Password Credentials

Direct username/password exchange

Least secure and should only be used when other flows are not possible.

Access Tokens

What are Access Tokens?

Access tokens are credentials used to access protected resources. They represent the authorization granted to the client.

Characteristics:

  • Short-lived (typically 15 minutes to 1 hour)
  • Stateless
  • Can be revoked
  • Contain scopes defining permissions

Token Types

JWT (JSON Web Tokens):

  • Self-contained with embedded claims
  • Can be validated without database lookup
  • Larger size but more efficient

Reference Tokens:

  • Random strings that reference stored data
  • Require database lookup for validation
  • Smaller size but less efficient

Refresh Tokens

Refresh tokens are long-lived credentials used to obtain new access tokens when they expire.

Benefits:

  • Users don't need to re-authenticate frequently
  • Access tokens remain short-lived for security
  • Better user experience

Security considerations:

  • Store securely (encrypted, HTTP-only cookies)
  • Implement proper rotation
  • Monitor for suspicious activity

OAuth Scopes

Scopes define the level of access that an application has to a user's account.

Common examples:

  • read: Read-only access to user data
  • write: Ability to modify user data
  • admin: Administrative access
  • email: Access to email address
  • profile: Access to profile information

Best practices:

  • Request minimal scopes needed
  • Clearly explain what each scope means
  • Allow users to deny specific scopes

Security Best Practices

Client Security

  • Store client secrets securely
  • Use HTTPS for all communications
  • Implement proper redirect URI validation
  • Use state parameter to prevent CSRF attacks

Token Security

  • Keep access tokens short-lived
  • Store refresh tokens securely
  • Implement token rotation
  • Monitor for token abuse

Server Security

  • Validate all requests
  • Implement rate limiting
  • Log security events
  • Regular security audits

Common OAuth Providers

Google OAuth 2.0

Widely used for Google services integration.

Scopes:

  • https://www.googleapis.com/auth/userinfo.profile
  • https://www.googleapis.com/auth/userinfo.email

GitHub OAuth 2.0

Popular for developer tools and applications.

Scopes:

  • user: Access user profile data
  • repo: Access repository data
  • admin:org: Manage organisation settings

Facebook OAuth 2.0

Common for social media integrations.

Scopes:

  • email: Access email address
  • public_profile: Access public profile
  • user_posts: Access user posts

Implementation Examples

Node.js with Express

const express = require('express');
const axios = require('axios');

const app = express();

// OAuth configuration
const oauthConfig = {
  clientId: process.env.CLIENT_ID,
  clientSecret: process.env.CLIENT_SECRET,
  redirectUri: 'http://localhost:3000/callback',
  authUrl: 'https://accounts.google.com/oauth/authorize',
  tokenUrl: 'https://oauth2.googleapis.com/token'
};

// Start OAuth flow
app.get('/auth', (req, res) => {
  const authUrl = `${oauthConfig.authUrl}?` +
    `client_id=${oauthConfig.clientId}&` +
    `redirect_uri=${oauthConfig.redirectUri}&` +
    `response_type=code&` +
    `scope=email profile&` +
    `state=${Math.random().toString(36).substring(7)}`;
  
  res.redirect(authUrl);
});

// Handle OAuth callback
app.get('/callback', async (req, res) => {
  const { code } = req.query;
  
  try {
    const tokenResponse = await axios.post(oauthConfig.tokenUrl, {
      client_id: oauthConfig.clientId,
      client_secret: oauthConfig.clientSecret,
      code: code,
      grant_type: 'authorization_code',
      redirect_uri: oauthConfig.redirectUri
    });
    
    const { access_token, refresh_token } = tokenResponse.data;
    
    // Store tokens securely and redirect to app
    res.redirect('/dashboard');
  } catch (error) {
    res.status(500).send('Authentication failed');
  }
});

Python with Flask

from flask import Flask, request, redirect, session
import requests
import os

app = Flask(__name__)
app.secret_key = os.urandom(24)

# OAuth configuration
OAUTH_CONFIG = {
    'client_id': os.environ.get('CLIENT_ID'),
    'client_secret': os.environ.get('CLIENT_SECRET'),
    'redirect_uri': 'http://localhost:5000/callback',
    'auth_url': 'https://accounts.google.com/oauth/authorize',
    'token_url': 'https://oauth2.googleapis.com/token'
}

@app.route('/auth')
def auth():
    auth_url = f"{OAUTH_CONFIG['auth_url']}?" + \
               f"client_id={OAUTH_CONFIG['client_id']}&" + \
               f"redirect_uri={OAUTH_CONFIG['redirect_uri']}&" + \
               f"response_type=code&" + \
               f"scope=email profile&" + \
               f"state={os.urandom(16).hex()}"
    
    return redirect(auth_url)

@app.route('/callback')
def callback():
    code = request.args.get('code')
    
    # Exchange code for tokens
    token_data = {
        'client_id': OAUTH_CONFIG['client_id'],
        'client_secret': OAUTH_CONFIG['client_secret'],
        'code': code,
        'grant_type': 'authorization_code',
        'redirect_uri': OAUTH_CONFIG['redirect_uri']
    }
    
    response = requests.post(OAUTH_CONFIG['token_url'], data=token_data)
    
    if response.status_code == 200:
        tokens = response.json()
        session['access_token'] = tokens['access_token']
        session['refresh_token'] = tokens.get('refresh_token')
        return redirect('/dashboard')
    else:
        return 'Authentication failed', 500

Common Challenges and Solutions

Token Expiration

Challenge: Access tokens expire, requiring re-authentication.

Solution: Implement automatic token refresh using refresh tokens.

Security Vulnerabilities

Challenge: OAuth implementations can have security flaws.

Solution: Follow OAuth 2.0 security best practices and use established libraries.

User Experience

Challenge: OAuth flows can be complex and confusing.

Solution: Clear messaging, progress indicators and error handling.

Testing OAuth Implementations

Test Scenarios

  • Valid authorisation flow
  • Invalid client credentials
  • Expired tokens
  • Malformed requests
  • CSRF protection
  • Redirect URI validation

Testing Tools

  • OAuth 2.0 testing tools
  • Postman collections
  • Automated test suites
  • Security scanners

Monitoring and Analytics

Key Metrics

  • Authentication success rates
  • Token usage patterns
  • Error rates by provider
  • User consent rates

Security Monitoring

  • Failed authentication attempts
  • Token abuse patterns
  • Unusual access patterns
  • Security event logging

Future of OAuth

OAuth 2.1

The next version of OAuth with improved security defaults.

Key changes:

  • PKCE required for public clients
  • Refresh token rotation
  • Improved security requirements

Industry Trends

  • Increased focus on security
  • Better user experience
  • Integration with modern identity standards
  • Enhanced privacy controls

Conclusion

OAuth 2.0 is essential for modern application development, providing secure and standardised ways to handle authorisation. Understanding its principles, implementation patterns and security considerations is crucial for building robust applications that integrate with third-party services.

When implementing OAuth 2.0, always prioritise security, follow best practices and consider the user experience. Use established libraries and frameworks to avoid common pitfalls and ensure compliance with the specification.