π OWASP API Security: Authentication and Authorization
Introduction: This comprehensive guide covers API authentication and authorization
mechanisms, security principles, and best practices for securing application programming interfaces.
π What is an API?
An Application Programming Interface (API) is a set of protocols and tools that allow
different software applications to communicate with each other. APIs need robust security measures, just
like any other component of your application infrastructure.
Unlike browsers that automatically manage sessions and cookies, when working with APIs, your application
must manually handle authentication tokens and session management. This requires careful implementation of
security mechanisms.
π Core Authentication Concept
Authentication Flow Diagram
User (JFK)
β
Token Endpoint
β
Receive Token (2345)
β
Weather API Request
β
Response
Example Scenario: Johnny's Weather API
Step 1: JFK wants to check the weather to decide if he needs an umbrella.
Step 2: First, JFK must authenticate by sending credentials to the token endpoint.
Step 3: The API validates credentials and returns a token (e.g., token: 2345).
Step 4: JFK stores this token and includes it in subsequent API requests.
Step 5: Before the token expires (typically 1 hour), JFK must refresh it using the
refresh endpoint.
β οΈ Security Principle: Tokens have expiration times for security reasons. This limits the
window of opportunity if a token is compromised. Always implement token refresh mechanisms before
expiration.
π Authentication Methods
1. Basic Authentication
Basic Authentication is one of the simplest authentication methods. It involves encoding the username and
password in Base64 and sending them with each request.
Basic Authentication Flow
Client
β
Base64 Encode Credentials
β
Add Authorization Header
β
Weather API
β
Verify & Respond
Basic Authentication Header Format:
Authorization: Basic [base64_encoded_credentials]
username:password | base64
Postman Configuration for Basic Auth:
In Postman, you can configure Basic Authentication at two levels:
Collection Level: Set authentication once, and it applies to all requests in the
collection
Request Level: Override collection-level auth for specific requests
Postman automatically converts username and password into the proper Base64 authorization header.
π¨ Critical Security Warning: If you encounter Basic Authentication over HTTP (not HTTPS)
during penetration testing, report it immediately! This is a critical vulnerability as credentials are
transmitted in easily decodable Base64 format. Always recommend migrating to HTTPS and preferably to more
secure authentication methods like API keys or OAuth 2.0.
π‘ Best Practice: Avoid using Basic Authentication in production environments. If
credentials leak, both username and password are compromised. API keys are preferable because they can be
revoked without requiring password changes for user accounts.
2. API Key Authentication
API Keys provide a more flexible authentication mechanism. They are unique identifiers that can be revoked
independently without affecting user credentials.
π OpenAPI Specification Example: API keys can be defined in headers or cookies. The
specification allows defining security schemes with type "apiKey" and specifying the location (header,
query, or cookie).
π‘ Security Tip for Bug Bounties: Search GitHub repositories for exposed API keys using
Google Dorks. If you know the API key format (e.g., starts with "src_"), you can search for patterns like:
site:github.com "src_" [company_name]
β οΈ Important Note: Distinguish between public and private API keys. Public API keys (like
for maps or analytics) are meant to be exposed. Always test if an API key grants unauthorized access before
reporting it as a vulnerability.
3. Bearer Token / JWT Authentication
Bearer tokens, especially JSON Web Tokens (JWT), are widely used for stateless authentication. The token
contains encoded information about the user and their permissions.
π Token Refresh: JWT tokens typically expire after a short period (e.g., 1 hour).
Implement a refresh token mechanism to obtain new access tokens without requiring users to re-authenticate.
4. OAuth 2.0 Authentication
OAuth 2.0 is an industry-standard authorization framework that enables applications to obtain limited access
to user accounts. It's commonly used for third-party integrations.
OAuth 2.0 Authorization Code Flow
Authorization Request
β
User Approves
β
Authorization Code
β
Token Request
β
Access Token
OAuth 2.0 Components:
Client ID: Public identifier for the app
Client Secret: Private key for authentication
Authorization URL: Where users grant permission
Token URL: Exchange code for access token
Callback URL: Where auth response is sent
OAuth 2.0 Parameters:
State: CSRF protection parameter
Scope: Requested permissions
Nonce: Prevents replay attacks
Response Type: Desired response format
Grant Type: Authorization method
OAuth 2.0 Authorization Request Example:
GET
/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=CALLBACK_URL&scope=openid profile
email&state=RANDOM_STATE
Token Exchange Request:
POST /token -d
"grant_type=authorization_code&code=AUTH_CODE&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&redirect_uri=CALLBACK_URL"
π State Parameter Security: The state parameter is crucial for CSRF protection. Always
verify that the state returned matches the state you sent. Store the state value before redirecting to the
authorization URL and validate it upon callback.
π‘ OAuth Playground: Use the OAuth 2.0 Playground to test and understand different OAuth
flows interactively. This helps visualize the authorization process and token exchange mechanisms.
5. OpenID Connect (OIDC)
OpenID Connect is an identity layer built on top of OAuth 2.0. It adds an ID token that contains user
information in JWT format.
OIDC Authorization Request:
GET /authorize?response_type=code&client_id=CLIENT_ID&
redirect_uri=CALLBACK_URL&scope=openid profile email&
state=STATE&nonce=NONCE
ID Token Contents (Decoded JWT):
Claim
Description
sub
Subject (user identifier)
email
User's email address
name
User's full name
iat
Issued at timestamp
exp
Expiration timestamp
aud
Audience (intended recipient)
π‘οΈ Authorization Models
Role-Based Access Control (RBAC)
RBAC assigns permissions based on user roles. Users are assigned to roles, and roles are granted specific
permissions.
RBAC Structure
User
β
Assigned Role
β
Role Permissions
β
Access Resources
RBAC Example: Hospital System
Role
Permissions
Doctor
Read/Write patient records, prescribe medication
Nurse
Read patient records, update vital signs
Admin
Manage users, configure system settings
Patient
Read own records, request appointments
Attribute-Based Access Control (ABAC)
ABAC is more dynamic than RBAC. It evaluates access based on attributes of the user, resource, and
environment.
ABAC Attributes:
User Attributes: Role, department, clearance level
Environment Attributes: Time, location, IP address
Action Attributes: Read, write, delete, modify
ABAC Example Policy:
A doctor can access patient records only if:
They are currently on shift
They are physically in the hospital
The patient is assigned to them
It's within business hours
π RBAC vs ABAC: RBAC is simpler to implement and manage but less flexible. ABAC provides
fine-grained control and adapts to dynamic conditions but requires more complex policy management.
π Testing Authentication in Postman
Postman Authentication Configuration:
Collection-Level Auth: Set authentication once for all requests in a collection
Request-Level Auth: Override collection auth for specific requests
Inherit from Parent: Requests automatically use collection-level auth unless
overridden
Authorization Tab β Select Auth Type (Basic, Bearer Token, API Key, OAuth 2.0, etc.)
π― Security Best Practices
Do's:
β Always use HTTPS for API communications
β Implement token expiration and refresh mechanisms
Visit jwt.io and paste your JWT token to decode and inspect its contents
Testing OAuth 2.0 Flows:
Visit OAuth 2.0 Playground to interactively test different OAuth flows
π Summary
API authentication and authorization are critical components of API security. Understanding the different
methodsβBasic Authentication, API Keys, Bearer Tokens, OAuth 2.0, and OpenID Connectβenables you to
implement appropriate security measures for your APIs.
π‘ Key Takeaways:
Always implement token expiration and refresh mechanisms
Choose authentication methods appropriate for your use case
Implement proper authorization controls (RBAC or ABAC)
Test thoroughly using tools like Postman or cURL
Follow security best practices and never transmit credentials over HTTP
Regularly audit and rotate API keys and tokens
β οΈ Final Security Reminder: Security is an ongoing process. Regularly review your
authentication mechanisms, stay updated on security vulnerabilities, and implement defense-in-depth
strategies to protect your APIs.