Authorization Header
Introduction
Most modern APIs do not allow anonymous access to sensitive resources. Before a client can access user profiles, banking information, payment details, order history, health records, administrative functions, or private business data, the server must verify who the client is and whether that client is allowed to perform the requested action. The standard HTTP request header used to send authentication credentials to the server is the Authorization header.
The Authorization header is one of the most important headers in API development, API security, and API testing. It is used in login flows, OAuth 2.0 integrations, JWT-based authentication, Basic authentication, API-key security, service-to-service communication, mobile app APIs, backend integrations, and automation frameworks. If this header is missing, malformed, expired, or tampered with, the API should reject the request in a controlled and secure way.
For API testers, Authorization header testing is not optional. A protected API must be tested with valid credentials, missing credentials, invalid credentials, expired credentials, insufficient permissions, tampered tokens, wrong roles, wrong tenants, and unsafe transport conditions. These tests prove that the API does not expose private data, does not allow privilege escalation, and does not confuse authentication failures with authorization failures.
What Is the Authorization Header?
The Authorization header is an HTTP request header used to send authentication credentials from the client to the server. The server reads these credentials, validates them, identifies the client or user, and then decides whether the requested resource or action should be allowed.
A simple definition is this: the Authorization header carries authentication credentials that allow a client to access protected API resources. The general format is:
Authorization: <Authentication-Scheme> <Credentials>
A common bearer-token example is:
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Here, Bearer is the authentication scheme and the long token value is the credential. The exact meaning of the credential depends on the authentication approach used by the API. It may be a JWT, OAuth access token, Basic authentication value, signed token, or another credential format.
Why the Authorization Header Is Needed
Consider a banking API endpoint such as GET /accounts/101. Without authentication, anyone who knows or guesses the account ID could attempt to view another customer's account details. That would be a serious security failure. Instead, the client must send credentials, such as a bearer token, in the Authorization header. The server validates the token before returning account information.
The Authorization header allows the API to answer two questions. First, who is making the request? This is authentication. Second, what is that authenticated identity allowed to do? This is authorization. Both checks are needed. A user may be logged in correctly but still not allowed to access an admin endpoint, another tenant's data, or another user's private records.
Without the Authorization header or an equivalent credential mechanism, protected APIs could not reliably enforce access control. Anyone could call private endpoints, automated scripts could scrape sensitive data, and applications could not safely separate users, roles, organizations, subscriptions, or permissions.
Where the Authorization Header Is Used
The Authorization header is sent in HTTP requests. It is typically placed after the request line along with other request headers such as Host, Accept, Content-Type, User-Agent, and custom headers. A protected API request may look like this:
GET /profile HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGc...
Accept: application/json
The server receives the request, extracts the Authorization header, validates the credential, identifies the user or client, checks permissions, and then returns the response. If the header is missing or invalid, the API normally returns 401 Unauthorized. If the credential is valid but the user lacks permission, the API normally returns 403 Forbidden.
Authorization is not normally sent in response headers. A login API may return a token in the response body or set a cookie, depending on the design, but protected requests send credentials from client to server. This direction matters when writing API tests because the tester must configure request headers correctly.
Authentication vs Authorization
Authentication and authorization are often confused. Authentication verifies identity. It answers, "Who are you?" Authorization verifies permissions. It answers, "What are you allowed to do?" Authentication happens first. Authorization happens after identity is known.
A common flow is straightforward. The user submits username and password. The server verifies the credentials. If login succeeds, the server issues a token. The client stores the token and sends it in the Authorization header on later requests. The server validates the token and then checks whether the user has permission to access the requested endpoint or resource.
This difference directly affects API status codes. Missing, invalid, malformed, or expired credentials usually produce 401 Unauthorized. Valid credentials with insufficient permission usually produce 403 Forbidden. A user who is not logged in should not receive the same response as a logged-in user who lacks admin permission, unless the API intentionally hides resource existence for security reasons.
Common Authorization Schemes
The Authorization header supports different authentication schemes. The most common in REST APIs are Bearer authentication and Basic authentication. Other systems may use Digest authentication, API key schemes, AWS Signature-style request signing, or custom enterprise authentication formats.
Bearer authentication is widely used with OAuth 2.0 and JWT-based APIs. Basic authentication sends a username and password encoded with Base64. Digest authentication uses a challenge-response mechanism. API key authentication may use the Authorization header or a custom header such as X-API-Key. AWS Signature authentication signs requests so the server can verify both identity and request integrity.
For testers, the scheme matters because each one has different validation rules. A bearer token can expire, be revoked, have invalid claims, or have a broken signature. Basic authentication can fail because credentials are wrong or encoding is malformed. API keys can be missing, disabled, scoped incorrectly, or used from an unauthorized client.
Bearer Authentication
Bearer authentication uses an access token. Whoever possesses the token can access the protected resource if the token is valid and has the required permissions. This is why it is called a bearer token: the bearer of the token can use it. A typical header looks like this:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR...
The token is often a JWT, but not every bearer token is necessarily a JWT. Some systems use opaque tokens that only the authorization server can interpret. In either case, the API validates the token before allowing access.
A typical flow begins with login. The user sends credentials to an authentication server. The server validates the credentials and generates an access token. The client stores the token and sends it in the Authorization header on protected API requests. The API validates the token and returns the resource only if validation succeeds.
Bearer tokens must be protected carefully. If an attacker obtains a valid bearer token, they may be able to use it until it expires or is revoked. This is why bearer tokens should be transmitted only over HTTPS, stored securely, kept short-lived where appropriate, and never exposed in logs or screenshots.
Basic Authentication
Basic authentication sends a username and password encoded using Base64. For example, if the username is john and the password is secret123, the combined value john:secret123 is Base64 encoded and sent like this:
Authorization: Basic am9objpzZWNyZXQxMjM=
The important point is that Base64 is encoding, not encryption. Anyone who obtains the header value can decode it. Basic authentication should therefore be used only over HTTPS, and many modern public APIs prefer bearer tokens or stronger authentication mechanisms instead.
Basic authentication is still used in some internal tools, legacy APIs, simple service integrations, and development environments. API testers should validate valid credentials, missing credentials, wrong password, malformed Base64, unsupported scheme, and HTTPS enforcement if required. They should also ensure that credentials are masked in logs and reports.
API Key Authentication
Some APIs use API keys instead of bearer tokens. API keys can be sent in a custom header such as:
X-API-Key: ABC123XYZ
or in the Authorization header with a custom scheme:
Authorization: ApiKey ABC123XYZ
The exact format depends on the API design. API keys are common for third-party integrations, server-to-server APIs, public developer platforms, monitoring APIs, and internal service calls. An API key may identify the calling application rather than a human user.
Testing API keys involves missing key, invalid key, disabled key, expired key, wrong environment key, wrong scope, quota exceeded, and attempts to access resources outside the key's permission. API keys should not be placed in URLs unless there is a very specific and safe reason, because URLs are commonly stored in logs, browser history, analytics, and monitoring systems.
Authorization Flow
A common authorization flow begins when the client logs in or obtains credentials from an identity provider. The authentication server validates the username, password, client ID, secret, authorization code, refresh token, certificate, or other credential. If validation succeeds, the server issues an access token or session credential.
The client then calls a protected API and sends the credential in the Authorization header. The API server validates the credential. With JWT, it may validate signature, expiration, issuer, audience, scopes, roles, and claims. With opaque tokens, it may call an authorization server or token introspection endpoint. With API keys, it may look up the key, owner, scopes, and limits.
After authentication, the API performs authorization checks. It verifies whether the authenticated identity can access the requested operation and resource. A user may have permission to view their own profile but not another user's profile. A support user may view cases but not payment data. An admin may access organization settings, while a normal user cannot.
Authorization Header Example
A protected request may look like this:
GET /users/101 HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGc...
Accept: application/json
If the token is valid and the user has permission, the server may respond:
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 101,
"name": "John"
}
This response proves only the successful path. A strong API test suite also checks missing Authorization, invalid token, expired token, malformed scheme, tampered token, valid token without permission, wrong tenant, and access to another user's resource.
Authorization behavior should also be consistent across endpoints. If one protected endpoint correctly requires a token but another similar endpoint accidentally allows anonymous access, that is a serious security defect. Testers should not validate one endpoint and assume all others are protected.
Missing Authorization Header
If a protected endpoint receives no Authorization header, the server should normally reject the request with 401 Unauthorized. This means authentication credentials are required but were not provided.
GET /profile
A typical response is:
HTTP/1.1 401 Unauthorized
Testing missing headers is simple but important. Automation frameworks often apply default headers globally, so a missing-header test must intentionally remove the default Authorization header. Otherwise the test may not actually validate the missing-header scenario.
The error response should be controlled and should not expose internal security logic. It may say authentication is required, but it should not reveal sensitive validation details. If the API uses JSON error responses, the 401 response should follow the same error schema.
Invalid Authorization Header
An invalid Authorization header may contain a malformed token, unsupported scheme, wrong prefix, corrupted value, or credentials that the server cannot validate. For example:
Authorization: Bearer InvalidToken
The server should normally respond with 401 Unauthorized. The client may need to obtain a new token or correct the request.
Test invalid formats deliberately. Send a token without the expected Bearer prefix, a blank token, a token with extra spaces, a token signed by the wrong key, a token with invalid structure, and a token intended for another environment. These tests prove that the server is not accepting credentials casually.
Error messages should be safe. A response should not expose signing keys, token parsing internals, framework stack traces, or whether a specific user account exists. Detailed security logs can be kept internally, but public responses should remain controlled.
Expired Tokens
Access tokens often expire. Expiration limits the damage if a token is leaked and forces clients to refresh credentials periodically. When a client sends an expired token, the API should reject it, usually with 401 Unauthorized.
Authorization: Bearer ExpiredToken
The client may then refresh the token using a refresh flow or ask the user to log in again. The exact behavior depends on the authentication design. APIs should distinguish expired tokens from insufficient permissions. An expired token means the identity is no longer authenticated for the request. Insufficient permission means the user is authenticated but not allowed.
Testing expired tokens is important because time-based security defects are common. Verify that expired tokens are rejected, tokens with future not-before times are handled correctly, refresh flow works if supported, revoked refresh tokens fail, and clocks are synchronized enough to avoid inconsistent behavior across services.
Insufficient Permissions
A valid token does not automatically allow every operation. A user may authenticate successfully but lack permission for a specific endpoint, resource, tenant, or action. In that case, the API should normally return 403 Forbidden.
GET /admin/users
Authorization: Bearer ValidUserToken
If the token belongs to a normal user, the server may respond:
HTTP/1.1 403 Forbidden
Authorization testing should cover roles, permissions, scopes, resource ownership, tenant boundaries, subscription levels, feature flags, and administrative access. A valid user should not be able to view another user's account, modify another tenant's data, approve restricted workflows, or call admin-only APIs.
Some APIs return 404 instead of 403 to hide whether a sensitive resource exists. That can be acceptable if it is an intentional, documented security pattern. It should not happen accidentally or inconsistently.
Authorization Header in OAuth 2.0
OAuth 2.0 commonly uses bearer access tokens in the Authorization header:
Authorization: Bearer <Access_Token>
OAuth separates the process of obtaining an access token from the process of using the token. A client may obtain a token through authorization code flow, client credentials flow, password flow in legacy systems, device code flow, or another supported grant. Once the token is obtained, it is sent to protected APIs using the Authorization header.
Testing OAuth-based APIs requires understanding token scope, audience, issuer, expiration, refresh behavior, and client permissions. A token issued for one API should not be accepted by a different API unless intended. A token without the required scope should not perform restricted actions. A token from a test identity provider should not be accepted in production unless explicitly configured.
Authorization Header in JWT
JWT, or JSON Web Token, is commonly used as a bearer token format. A JWT usually contains header, payload, and signature sections. The payload may include claims such as subject, issuer, audience, expiration, issued time, roles, scopes, tenant ID, and user information. The server validates the signature and claims before granting access.
A JWT-style Authorization header looks like this:
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Testing JWT validation should include signature tampering, expired tokens, wrong issuer, wrong audience, missing required claims, invalid role claims, changed payload, not-before claims, and algorithm-related restrictions. A dangerous implementation may decode JWT payloads without verifying signatures. Tests should make sure tampered tokens are rejected.
JWT payloads are encoded, not encrypted by default. Anyone with the token can often decode and read the claims. Do not place secrets or highly sensitive information inside JWT payloads unless the token is encrypted and the design explicitly supports it.
Authorization Header in API Testing
API testers should validate the Authorization header through positive and negative scenarios. The valid-token test verifies that a properly authenticated and authorized user can access the expected resource. This confirms the happy path.
Missing-header testing verifies that protected endpoints do not allow anonymous access. Invalid-token testing verifies that malformed, corrupted, unknown, or incorrectly signed credentials are rejected. Expired-token testing verifies that time-based security rules are enforced. Permission testing verifies that authenticated users cannot perform operations outside their authority.
Token tampering is especially important. Modify the signature, payload, expiration, issuer, audience, scope, role, or tenant claim. The server should reject tampered tokens. If it accepts a modified token, the API has a serious security defect.
Testers should also verify consistent status codes, error schemas, and traceability. 401 and 403 responses should be consistent and should not leak sensitive internals. Logs should capture enough information for security investigation while masking sensitive token values.
Real-World Examples
In a streaming application, a user logs in with credentials. The service validates the credentials and returns an access token. Every subsequent request for movies, watch history, account preferences, or subscription details includes Authorization: Bearer eyJhbGc.... The server validates the token before returning personalized content.
In a banking application, a request such as GET /accounts must include a valid Authorization header. Without the token, the API returns 401. With an invalid or expired token, it also returns 401. With a valid token for a user who is not allowed to access a specific account, it returns 403 or a documented security-friendly alternative.
In a partner API, an external company may send an API key. The key identifies the partner application and determines which endpoints, rate limits, and data scopes apply. Tests should verify that one partner's key cannot access another partner's data.
In an internal microservice architecture, one service may call another using a signed token or client credentials token. Service-to-service authentication should still be tested. Internal does not mean unrestricted.
Security Best Practices
Always use HTTPS when transmitting authorization credentials. Sending tokens over plain HTTP can expose them to interception. APIs should redirect or reject insecure traffic according to the platform security policy, and tests should confirm that credentials are not accepted over unsafe channels where HTTPS is required.
Use short-lived access tokens where appropriate. Short lifetimes reduce risk if a token is leaked. If refresh tokens are used, protect them more strongly and validate revocation behavior. Expiration, refresh, and logout behavior should be tested as part of authentication flows.
Never expose tokens in logs, browser consoles, error messages, screenshots, downloadable reports, or analytics tools. Automation frameworks should mask Authorization headers in reports and CI output. A test failure should not leak a real credential.
Follow the API's authentication specification. If the API expects Authorization: Bearer <token>, do not send the token without the Bearer prefix. If the API uses OAuth scopes, validate scope behavior. If the API uses tenant claims, validate tenant isolation. Apply the principle of least privilege when assigning permissions.
Common Mistakes
A common mistake is sending tokens over HTTP instead of HTTPS. This can expose credentials to interception. Protected APIs should use secure transport, and test environments should be configured to reflect production security expectations as much as possible.
Another mistake is missing the required authentication scheme prefix. For bearer authentication, this is wrong:
Authorization: eyJhbGc...
This is correct when the API expects bearer authentication:
Authorization: Bearer eyJhbGc...
A third mistake is confusing 401 and 403. 401 means authentication is missing, invalid, or expired. 403 means authentication succeeded, but the user lacks permission. This difference matters because clients react differently to these responses.
Logging sensitive tokens is another serious mistake. Test automation often prints request details during failures. If Authorization headers are not masked, real credentials may appear in CI logs or reports. This should be prevented at framework level.
Teams also sometimes validate only login and ignore authorization. A token may be valid, but permissions still need testing. Broken access control often appears when a valid user accesses the wrong resource.
Troubleshooting Authorization Header Issues
When an API returns an unexpected authentication or authorization error, first inspect the raw request. Confirm that the Authorization header is present, the scheme is correct, the token value is not empty, and no extra characters or whitespace were introduced. Copying tokens manually can introduce subtle formatting problems.
Next, verify token validity. Check whether the token is expired, revoked, issued by the expected identity provider, intended for the correct audience, and scoped for the requested operation. In distributed systems, also check whether all services trust the same issuer and signing keys.
If the response is 403, inspect permissions rather than token validity alone. Does the user have the required role? Does the token include the required scope? Does the user belong to the correct tenant or organization? Is the resource owned by that user? Is a feature flag or subscription level required?
Finally, compare behavior across environments. A token generated in QA should not normally work in production. A staging gateway may use different signing keys from local development. Environment mismatch is a common cause of valid-looking tokens failing authorization checks.
Authorization Header in Service-to-Service APIs
The Authorization header is not limited to browser users or mobile app users. In enterprise systems, many API calls happen between backend services. A payment service may call an invoice service, an order service may call an inventory service, and a reporting service may call several internal APIs to collect business data. These calls still need controlled access. If every internal service can call every endpoint without proof of identity, the system becomes difficult to secure, audit, and troubleshoot.
Service-to-service authorization commonly uses client credentials, signed tokens, mutual TLS, or platform-issued identity tokens. The consuming service receives or generates a credential and sends it in the Authorization header when calling another service. The provider service validates the credential, checks the calling application's identity, verifies scopes or permissions, and decides whether the operation should continue. This approach allows internal APIs to enforce least privilege instead of trusting the network location alone.
Testing service-to-service authorization requires more than confirming that the happy path works. Testers should verify that one service cannot call endpoints outside its allowed scope, that old credentials stop working after rotation, that tokens issued for one environment are rejected in another, and that missing internal credentials are handled consistently. These checks are important because service credentials often have broader permissions than normal user tokens. A leaked or over-permissioned service token can create serious business risk.
Another practical concern is observability. When an internal authorization failure happens, logs should identify the calling service, target endpoint, correlation id, and rejection reason without printing the actual token. This helps engineers debug failures while protecting secrets. Automated tests can validate response codes and error shapes, while security review can confirm that sensitive headers are masked in logs and reports.
Designing Automation Around Authorization Headers
A maintainable API automation framework should centralize Authorization header handling. Test code should not manually build token strings in every scenario. Instead, token generation, token refresh, header creation, and secret masking should live in reusable helper methods or client classes. This keeps tests readable and reduces the chance of inconsistent header formats across the suite.
For example, a test should express intent such as "call the order API as an approved customer" rather than repeatedly showing low-level token construction. The framework can then obtain the correct token, attach Authorization: Bearer <token>, and send the request. Negative tests can deliberately request no token, an expired token, a token with the wrong scope, or a token for another tenant. By controlling these variations in one place, the suite becomes easier to maintain when the authentication provider or token format changes.
Automation should also separate real secrets from test logic. Tokens, client ids, client secrets, and API keys should come from secure configuration, environment variables, secret managers, or controlled test data setup. They should not be committed into source code, feature files, screenshots, exported reports, or sample documentation. When reports include request details, Authorization values should be replaced with masked text such as Bearer ****.
Good authorization testing balances security depth with stable execution. A smoke suite may verify that a valid token can access critical APIs and a missing token is rejected. A regression suite may include expired tokens, invalid schemes, wrong audiences, role restrictions, scope restrictions, tenant isolation, and revoked credentials. Security-focused suites may go further by testing tampered JWT payloads, algorithm confusion risks, replay behavior, and rate-limited authentication failures. The exact depth depends on the application's risk, but every protected API should have at least basic positive and negative Authorization header coverage.
Interview-Ready Explanation
The Authorization header is an HTTP request header used to send authentication credentials from the client to the server. It enables the server to verify the client's identity and determine whether the client has permission to access a protected resource. The common format is Authorization: <scheme> <credentials>.
Common schemes include Bearer tokens used with OAuth 2.0 and JWT, Basic authentication using Base64-encoded username and password, API key authentication, Digest authentication, and signed request mechanisms such as AWS Signature. In modern REST APIs, Bearer tokens are especially common.
In API testing, the Authorization header is validated by testing valid authentication, missing credentials, invalid tokens, expired tokens, insufficient permissions, token tampering, wrong scopes, wrong roles, and tenant isolation. Missing or invalid authentication usually returns 401 Unauthorized, while valid authentication without permission usually returns 403 Forbidden.
Key Takeaway
The Authorization header is the standard way for a client to send credentials to a protected API. It supports authentication and enables authorization decisions. Without it, APIs cannot safely protect private user data, administrative operations, payments, reports, or service-to-service communication.
For API testers, the practical rule is simple: never test only the happy path with a valid token. Test missing, invalid, expired, tampered, and insufficiently privileged credentials. Validate 401 vs 403 behavior, secure error messages, token masking, HTTPS usage, and access-control boundaries. Strong Authorization header testing is one of the most important defenses against broken access control in APIs.