Blog | G5 Cyber Security

OAuth 2.0 Authorization Code Format

TL;DR

The OAuth 2.0 authorization code is a temporary code exchanged for an access token. It doesn’t have a strict, universally defined format, but it *must* be random, sufficiently long (recommended 43-128 characters), and securely generated to prevent guessing or manipulation. It’s best practice to treat it as confidential.

Understanding the Authorization Code

When a user grants an application permission to access their resources on a resource server, the authorization server issues an authorization code. This code is then sent back to the application, which exchanges it for an access token. The access token is what the application actually uses to access the protected resources.

Is there a specific format?

No, there isn’t one single mandated format for authorization codes defined in the core OAuth 2.0 specification (RFC 6749). However, following best practices is crucial for security.

Best Practices for Authorization Code Generation and Handling

  1. Randomness: The code must be unpredictable. Use a cryptographically secure random number generator (CSPRNG).
  2. Length: A longer code makes it harder to guess or brute-force. The specification recommends at least 43 characters, but 128 is better.
  3. Character Set: Use a mix of alphanumeric characters (A-Z, a-z, 0-9) and potentially symbols. Avoid easily confused characters (e.g., I/l, O/0).
  4. Uniqueness: Ensure each code is unique to prevent replay attacks.
  5. Expiry Time: Authorization codes should have a short lifespan (typically 5-10 minutes) to limit the window of opportunity for misuse.
  6. Confidentiality: Treat authorization codes as sensitive information. Transport them securely (HTTPS only). Do not log or store them unnecessarily.

Example Code Generation (Python)

This is a simplified example and should be adapted for your specific environment and security requirements.

import secrets
import string

def generate_authorization_code(length=43):
  alphabet = string.ascii_letters + string.digits
  code = ''.join(secrets.choice(alphabet) for i in range(length))
  return code

# Example usage:
code = generate_authorization_code()
print(f"Generated Authorization Code: {code}")

Important Considerations

Checking Code Validity (Conceptual)

Your authorization server will typically handle this internally, but conceptually:

  1. Receive the authorization code from the application.
  2. Look up the code in your database/storage.
  3. Verify that:
    • The code exists.
    • The code hasn’t expired.
    • The client ID matches the expected client ID.
    • The redirect URI matches the registered redirect URI.
  4. If all checks pass, issue an access token and refresh token (if applicable).
Exit mobile version