Authentication vs Authorization
Introduction
Authentication and authorization are two of the most important security concepts in API testing. Most modern APIs are not open to every caller. They protect user data, business transactions, internal resources, payment functions, administrative actions, reports, documents, and configuration details. Before an API returns protected information or performs a sensitive operation, it usually asks two separate questions. First, who is making this request? Second, what is that caller allowed to do?
The first question is authentication. Authentication verifies identity. It checks whether the caller is a valid user, application, service, device, or client. The caller may prove identity using a username and password, an API key, a bearer token, a JSON Web Token, an OAuth access token, a client certificate, or another credential. If the credential is missing, expired, malformed, revoked, or invalid, the API should reject the request because it cannot trust the caller's identity.
The second question is authorization. Authorization verifies permissions. Once the API knows who the caller is, it must decide what that caller can access or perform. An authenticated employee may be allowed to view only their own profile. A manager may be allowed to approve timesheets. An administrator may be allowed to create users. A support agent may be allowed to view customer details but not change payment data. Authorization is therefore about roles, permissions, policies, ownership, resource access, and business rules.
These terms are often used together, and many people casually say "auth" for both. In real API testing, confusing them leads to weak coverage. A test that only checks whether a token is accepted does not prove that access control is correct. A test that only checks admin access does not prove that normal users are blocked from restricted actions. Secure API testing must validate authentication and authorization separately, then validate how they work together in real flows.
What Is Authentication?
Authentication is the process of verifying the identity of a user, client application, system, or service that attempts to access an API. It answers the question, "Who are you?" In a login flow, a user may submit a username and password. In a backend service-to-service flow, a client may present a certificate or token. In a public developer API, the caller may send an API key. In an OAuth-based system, the client may obtain an access token from an authorization server and send that token to the API.
A simple authentication flow starts when the client sends credentials. The API or identity provider validates those credentials. If the credentials are valid, the system establishes identity and may issue a token. The client then uses that token for future API calls. The API does not need to ask for the password on every request because the token represents the authenticated identity for a limited period. If the token is invalid or expired, the API should reject the request.
Authentication is not the same as permission. If John successfully logs in, the system knows the caller is John. That does not mean John can delete another employee, approve a bank transfer, view a private medical record, or change system settings. Authentication proves identity, but it does not automatically grant every action. This distinction is critical for testers because many security defects happen after identity is verified but before permission is checked correctly.
Common authentication methods include username and password, basic authentication, API keys, bearer tokens, OAuth 2.0 access tokens, JWTs, OpenID Connect identity tokens, client certificates, and mutual TLS. Each mechanism has different testing concerns. Basic authentication requires validating encoded credentials and secure transport. API keys require checking missing, invalid, disabled, leaked, or environment-specific keys. JWTs require checking signature, issuer, audience, expiry, claims, and token tampering. Client certificates require certificate trust, expiry, revocation, and mutual TLS configuration.
Authentication Example
Consider an API endpoint that returns employee records. The endpoint may require an authorization header with a bearer token:
GET /employees
Authorization: Bearer eyJhbGciOi...
When the server receives this request, it validates the token. It may check whether the token has a valid signature, whether the token was issued by a trusted identity provider, whether it has expired, whether it was revoked, whether the audience matches the API, and whether the token format is correct. If the token passes validation, the API considers the caller authenticated. If the token is missing or invalid, the API should return an authentication failure response.
In many APIs, authentication failures return `401 Unauthorized`. The name of this status code can be confusing because it uses the word unauthorized, but in practice it usually means the caller is not authenticated or did not provide valid credentials. A missing token, invalid token, expired token, malformed authorization header, or wrong API key commonly results in `401 Unauthorized`.
Authentication tests should not stop at the happy path. A tester should verify valid credentials, invalid credentials, missing credentials, expired tokens, revoked tokens, malformed tokens, wrong authentication scheme, disabled users, locked accounts, invalid API keys, invalid certificates, and token refresh behavior. If the API accepts expired or tampered credentials, the defect is serious because unauthorized callers may gain access.
What Is Authorization?
Authorization is the process of determining what an authenticated caller is allowed to access or perform. It answers the question, "What are you allowed to do?" After authentication succeeds, the API has identity context. That context may include user ID, organization ID, tenant ID, role, groups, scopes, permissions, claims, subscription plan, account status, or ownership information. The API uses that context to decide whether the requested operation should be allowed.
Authorization is where access control rules become visible. An admin may create users. A manager may update team members. An employee may view only their own profile. A guest may have read-only access. A customer may view their own orders but not another customer's orders. A paid subscriber may access premium content while a free user cannot. These are authorization decisions because they depend on identity plus permission.
Authorization failures usually return `403 Forbidden`. This means the API recognized the caller, but the caller does not have permission to perform the action. For example, an employee may successfully authenticate but still be forbidden from deleting another employee record. In that case, returning `401` would be misleading because identity was already verified. Returning `403` tells the client that access is denied due to insufficient permission.
Authorization can be implemented in several models. Role-Based Access Control, or RBAC, grants access based on roles such as Admin, Manager, Employee, or Guest. Attribute-Based Access Control, or ABAC, uses attributes such as department, region, account type, time, device, or classification. Policy-Based Access Control uses centralized rules or policies. Resource-Based Authorization checks ownership or relationship to a specific resource. Permission-Based Authorization grants explicit capabilities such as `employee:read`, `employee:delete`, or `order:approve`.
Authorization Example
Assume John is authenticated as a regular employee. He sends this request:
DELETE /employees/101
Authorization: Bearer employee-token
The API first validates John's token. If the token is valid, authentication succeeds. Next, the API checks whether John has permission to delete employee records. If John is a regular employee, the answer should be no. The API should reject the request with `403 Forbidden`. The failure is not because John is unknown. The failure is because John is not allowed to perform this operation.
This example shows why authentication and authorization must be tested separately. A valid employee token should work for allowed employee actions, such as viewing the employee's own profile. The same token should fail for restricted actions, such as deleting employee records, updating salary, accessing another employee's private data, or changing admin settings. Without role-based and resource-based tests, a serious authorization defect may remain hidden.
Authorization defects are often more subtle than authentication defects. A missing token is easy to detect. A broken ownership rule may be harder. For example, a customer may be able to change the order ID in the URL and access another customer's order. This is a classic authorization issue because the user is authenticated but should not be authorized for that resource. API testers must include cross-user and cross-tenant checks to catch these defects.
Authentication vs Authorization Workflow
A secure API request usually follows a predictable flow. The client sends a request with credentials or a token. The API validates identity. If identity validation fails, the API rejects the request. If identity validation succeeds, the API moves to authorization. The authorization layer checks whether the authenticated caller has permission for the requested endpoint, action, resource, and context. If permission is missing, the API rejects the request. If permission is sufficient, the API processes the request and returns the response.
This order matters. Authentication comes before authorization because the system cannot decide what a caller is allowed to do until it knows who the caller is. Anonymous access can exist for public endpoints, but protected endpoints still need a clear access decision. If a caller is anonymous, the API may either reject the request with `401` or allow limited public access depending on the endpoint. For private endpoints, identity must be established first.
A real-life analogy is entering an office building. Authentication is the security guard checking your ID card. The guard confirms that you are a real employee or visitor. Authorization is what happens after that: your access card determines whether you can enter the server room, HR office, finance area, conference floor, or only the lobby. Being known at the entrance does not mean you can access every room.
Key Differences
| Point | Authentication | Authorization |
|---|---|---|
| Main purpose | Verifies identity | Verifies permissions |
| Question answered | Who are you? | What are you allowed to do? |
| Execution order | Happens first | Happens after authentication |
| Inputs | Credentials, token, key, certificate | Roles, permissions, scopes, ownership, policies |
| Failure status | Usually 401 Unauthorized | Usually 403 Forbidden |
| Example | Validating a bearer token | Checking whether the user can delete an employee |
This table is useful for interviews, but testers should go deeper in real projects. Authentication can succeed while authorization fails. Authorization can be overly permissive even when authentication is strong. A strong login system does not protect the API if every authenticated user can access every endpoint. Similarly, excellent role rules are useless if the API accepts forged or expired tokens. Both layers must be correct.
HTTP 401 vs 403
HTTP status codes help clients and testers understand what kind of security failure occurred. `401 Unauthorized` usually means the request lacks valid authentication credentials. The token may be missing, expired, invalid, malformed, or supplied using the wrong scheme. The API may include a `WWW-Authenticate` response header depending on the authentication method. In API testing, `401` is expected when the caller cannot prove identity.
`403 Forbidden` means the caller is authenticated but not permitted to perform the requested action. The user may have a valid token, but the role, scope, policy, subscription level, tenant, or ownership rule does not allow access. In API testing, `403` is expected when identity is known but permission is insufficient.
| Scenario | Expected Status | Reason |
|---|---|---|
| No token supplied | 401 Unauthorized | The caller is not authenticated |
| Invalid token supplied | 401 Unauthorized | The identity cannot be trusted |
| Expired token supplied | 401 Unauthorized | The credential is no longer valid |
| Valid employee token used for admin action | 403 Forbidden | The caller lacks permission |
| Valid customer token used for another customer's order | 403 Forbidden or 404 Not Found | The caller should not access that resource |
Some APIs intentionally return `404 Not Found` instead of `403 Forbidden` for resources owned by another user. This can prevent attackers from learning whether a resource exists. That decision should be documented. Testers should not assume every authorization failure must be `403`; they should compare behavior with the API security design. However, the conceptual difference remains the same: `401` is about failed identity verification, while `403` is about denied permission.
Common Authentication Mechanisms
Basic authentication sends a username and password encoded in the authorization header. It is simple but should only be used over HTTPS because encoded is not the same as encrypted. API keys are shared secrets used to identify a calling application or developer account. They are common in public APIs, but they must be protected, rotated, and restricted. Bearer tokens are credentials that grant access to whoever presents them, so they must also be transmitted securely and stored carefully.
OAuth 2.0 is widely used for delegated authorization and token-based access. A client obtains an access token from an authorization server and sends it to the API. OpenID Connect builds identity features on top of OAuth 2.0 and is often used for login. JWTs are compact tokens that can carry claims such as issuer, subject, audience, expiry, roles, scopes, or tenant. A JWT must be validated carefully because trusting an unsigned, expired, or tampered token is a serious vulnerability.
Client certificates and mutual TLS are often used in enterprise or service-to-service APIs. With mutual TLS, both client and server prove identity using certificates. This is useful when systems need strong machine identity, such as internal microservices, partner integrations, banking connections, or B2B APIs. Testing certificate-based authentication requires different setup from token-based testing, but the principle is the same: the API must trust only valid clients.
Common Authorization Models
Role-Based Access Control is one of the most common authorization models. Users are assigned roles, and each role has allowed actions. For example, Admin can create, update, and delete users; Manager can view and update team records; Employee can view only personal details. RBAC is simple to understand and test, but it can become rigid if business rules are more complex than roles.
Attribute-Based Access Control uses attributes to make access decisions. A user may access a record only if the user's department matches the record's department, the request comes from an approved location, the account is active, and the data classification is not restricted. ABAC is more flexible than simple roles but requires careful testing because many combinations are possible.
Resource-based authorization focuses on ownership or relationship to a specific resource. A customer may view only orders belonging to that customer. A doctor may view only patients assigned to that doctor. A project member may update only tasks inside their project. These rules are critical in APIs because attackers often try to change path parameters, query parameters, or IDs in the request to access someone else's data.
Permission-based and scope-based models are also common. A token may include scopes such as `read:employees`, `write:employees`, or `delete:employees`. The API checks whether the token has the required scope for the operation. In OAuth-based APIs, scope validation is a major part of authorization testing. A token with read scope should not perform write operations.
Authentication in API Testing
Authentication testing verifies whether the API correctly accepts valid identity proof and rejects invalid identity proof. A tester should start with the happy path: valid credentials, valid token, valid API key, or valid certificate should allow the request to reach the next layer. Then the tester should cover negative cases. Missing credentials should fail. Invalid credentials should fail. Expired tokens should fail. Revoked tokens should fail. Tokens signed by the wrong issuer should fail. Tokens with the wrong audience should fail. Tokens with modified payloads should fail.
Token expiration and refresh behavior require special attention. Many APIs use short-lived access tokens and longer-lived refresh tokens. The tester should verify that expired access tokens are rejected, valid refresh tokens can obtain new access tokens, expired refresh tokens are rejected, revoked refresh tokens cannot be reused, and refresh flows do not create unlimited access. If the application has logout, the tester should verify whether logout revokes tokens or simply removes them from the client.
Authentication testing also includes lockout, rate limiting, brute force protection, password policy, multi-factor authentication, and account status rules when applicable. An API should not allow unlimited login attempts without controls. Disabled users should not authenticate. Locked accounts should be blocked. Password reset flows should not expose sensitive information. Error messages should be useful but not reveal whether a username exists if that would create enumeration risk.
Authorization in API Testing
Authorization testing verifies whether authenticated users can access only what they are allowed to access. This requires test users with different roles, permissions, organizations, tenants, subscription levels, or ownership relationships. A tester should not use only one admin account for all API tests. Admin-only testing hides authorization defects because admins are often allowed to do everything. Real security coverage requires admin, manager, employee, customer, guest, and other relevant roles.
Authorization tests should cover endpoint access, action access, field access, resource ownership, cross-user access, cross-tenant access, workflow state, and least privilege. Endpoint access checks whether a role can call a route. Action access checks whether the role can perform operations such as create, update, delete, approve, export, or refund. Field access checks whether sensitive fields are hidden or read-only. Resource ownership checks whether users can access only their own records. Cross-tenant tests check whether one organization can access another organization's data.
Authorization must also be tested for indirect access. For example, a user interface may hide the delete button from an employee, but the API must still reject a direct `DELETE` request. Security should not rely only on frontend controls. API testers should call restricted endpoints directly with lower-privilege tokens. If the backend accepts the request, the defect is serious even if the UI normally hides the option.
Example API Test Cases
| Area | Test Scenario | Expected Result |
|---|---|---|
| Authentication | Call protected endpoint with valid token | Request is accepted or proceeds to permission check |
| Authentication | Call protected endpoint without token | 401 Unauthorized |
| Authentication | Call protected endpoint with expired token | 401 Unauthorized |
| Authentication | Call protected endpoint with tampered JWT | 401 Unauthorized |
| Authorization | Admin deletes employee record | Allowed if admin policy permits it |
| Authorization | Employee deletes employee record | 403 Forbidden |
| Authorization | Customer views another customer's order | Denied according to API design |
| Authorization | Read-only token attempts update | 403 Forbidden |
These examples show how authentication and authorization coverage should work together. The tester first confirms that valid and invalid identity checks behave correctly. Then the tester checks whether the same authenticated users are restricted according to their roles and resources. This layered approach catches more defects than testing only successful requests.
REST Assured Example
In REST Assured, a happy path request with a bearer token may look like this:
given()
.header("Authorization", "Bearer " + token)
.when()
.get("/employees")
.then()
.statusCode(200);
An unauthenticated request can be tested by omitting the header:
given()
.when()
.get("/employees")
.then()
.statusCode(401);
An authorization failure can be tested by using a valid token for a user who lacks permission:
given()
.header("Authorization", "Bearer " + employeeToken)
.when()
.delete("/employees/101")
.then()
.statusCode(403);
The important point is that the forbidden test uses a valid token. If the token is invalid, the test is not proving authorization. It is only proving authentication failure. Test data should clearly separate invalid credentials from valid low-privilege credentials so failures are meaningful.
Postman and Karate Examples
In Postman, authentication tests often use the Authorization tab or manually set the `Authorization` header. A tester can create environments for admin, manager, employee, and guest tokens. Test scripts can assert status codes, response bodies, error messages, and headers. Postman is useful for exploring security behavior because tokens can be swapped quickly and requests can be organized into collections.
In Karate, a request with a token may look like this:
Given header Authorization = 'Bearer ' + token
When method GET
Then status 200
An authorization failure may be expressed as:
Given header Authorization = 'Bearer ' + employeeToken
When method DELETE
Then status 403
Regardless of tool, the same testing logic applies. Use valid credentials for positive authentication tests, invalid credentials for authentication failure tests, and valid low-privilege credentials for authorization failure tests. Keep the test intention clear so a failed test points to the correct security layer.
Real-World Examples
In banking, authentication may include username, password, OTP, device registration, biometric verification, or token validation. Authorization decides whether the customer can view an account, transfer funds, add a beneficiary, download statements, close an account, or approve a high-value transaction. A customer should not access another customer's account. A teller may have limited access. A branch manager may have additional approval permissions. Every role and resource relationship matters.
In healthcare, authentication verifies whether the caller is a doctor, nurse, patient, administrator, or partner system. Authorization decides which patient records that caller can view or update. A doctor may access assigned patient records. A patient may access only personal records. A billing user may access billing information but not clinical notes. A tester must validate privacy boundaries carefully because healthcare data is sensitive and regulated.
In e-commerce, authentication verifies customer or admin identity. Authorization decides whether a customer can view an order, cancel an order, request a refund, change a shipping address, or access admin product management. Customers should manage only their own orders. Admin users may manage many orders, but some actions may require higher privilege. Authorization defects in e-commerce can expose personal data, order history, payment-related details, or business operations.
In employee management systems, authentication verifies employee login. Authorization decides whether a regular employee can view personal details, whether HR can update employee records, whether managers can view team information, and whether payroll users can access salary data. Field-level authorization may be important because a user may view an employee name and department but not salary, tax ID, or personal documents.
Best Practices
Always authenticate before authorizing. Use secure authentication methods such as OAuth 2.0, OpenID Connect, JWT, API keys, or client certificates based on the system's needs. Protect all credentials in transit using HTTPS. Do not expose tokens in URLs. Expire tokens appropriately. Rotate API keys and secrets. Revoke tokens when needed. Validate token issuer, audience, expiry, signature, scopes, and claims according to the design.
Apply least privilege authorization. Users and clients should receive only the access they need. Avoid broad roles that grant unnecessary power. Validate access at the backend API layer, not only in the UI. Check role-based, scope-based, resource-based, and tenant-based rules. Include negative tests for each role. Test with real permission combinations instead of only admin accounts.
Log authentication and authorization failures for auditing, but avoid logging sensitive credentials or full tokens. Error messages should be clear enough for clients but not so detailed that attackers learn too much. For example, an API may avoid revealing whether a username exists. Security logs should help operations teams investigate repeated failures, suspicious access attempts, token misuse, and policy violations.
Common Mistakes
The most common mistake is confusing authentication with authorization. Authentication verifies identity. Authorization verifies permissions. A user can be authenticated and still forbidden. A valid token is not proof that every action should be allowed. Testers must use this distinction when designing scenarios and explaining failures.
Another mistake is returning the wrong status code. Missing or invalid credentials should usually return `401 Unauthorized`. Valid credentials with insufficient permission should usually return `403 Forbidden`, unless the API intentionally hides resource existence with `404 Not Found`. Incorrect status codes can confuse clients, weaken error handling, and make security behavior harder to test.
Granting excessive permissions is a serious design and testing problem. If every authenticated user can access admin endpoints, the API is vulnerable even if login is secure. If a token contains too many scopes, the client can perform operations beyond its purpose. If one tenant can access another tenant's records, the issue can become a major data breach.
Testing only successful scenarios is another weak practice. Security testing must include invalid credentials, missing tokens, expired tokens, revoked tokens, unauthorized roles, cross-user access, cross-tenant access, direct API calls that bypass the UI, and permission edge cases. Positive tests prove the system works for intended users. Negative tests prove it blocks unintended users.
Review Checklist
When reviewing authentication coverage, ask whether protected endpoints reject missing credentials, invalid credentials, expired tokens, revoked tokens, malformed headers, wrong token types, wrong issuers, wrong audiences, and disabled accounts. Ask whether token refresh, logout, password reset, account lockout, and multi-factor flows behave as expected. Ask whether credentials are protected in logs, URLs, browser storage, and error messages.
When reviewing authorization coverage, ask whether each role has only the required access. Check whether users can access records they do not own. Check whether one tenant can access another tenant's data. Check whether read-only users can perform write operations. Check whether hidden UI actions are still blocked by the API. Check whether field-level restrictions are enforced in responses. Check whether permission changes take effect correctly after role updates.
This checklist should be applied early in API design and repeatedly during testing. Authentication and authorization are not one-time checks. New endpoints, new roles, new scopes, new partners, and new workflows can introduce access control gaps. Strong teams make security validation part of normal API testing, not a final activity at the end of the release.
Interview Questions
A common interview question is: what is authentication? A strong answer is that authentication is the process of verifying the identity of a user, application, or client attempting to access an API. It answers "Who are you?" and may involve passwords, API keys, bearer tokens, JWTs, OAuth access tokens, or certificates.
Another common question is: what is authorization? Authorization is the process of determining what an authenticated user or client is allowed to access or perform. It answers "What are you allowed to do?" and may depend on roles, permissions, scopes, policies, ownership, tenant, or resource rules.
Interviewers often ask which comes first. Authentication comes first because the API must know the caller's identity before checking permissions. They may also ask the difference between `401` and `403`. A clear answer is that `401 Unauthorized` usually means authentication failed or credentials are missing, while `403 Forbidden` means authentication succeeded but the caller lacks permission.
For testing questions, explain that API testers should validate valid and invalid authentication, missing and expired tokens, token tampering, role-based access, resource ownership, cross-user access, cross-tenant access, least privilege, and negative security scenarios. Mention that using only admin credentials is poor coverage because it hides authorization defects.
Interview-Ready Explanation
Authentication and authorization are two separate API security processes. Authentication verifies identity and answers the question, "Who are you?" It confirms that the caller is a valid user, application, service, or client by checking credentials such as username and password, API key, bearer token, OAuth token, JWT, or client certificate. If authentication fails, protected APIs usually return `401 Unauthorized`.
Authorization happens after authentication and answers the question, "What are you allowed to do?" It checks roles, permissions, scopes, policies, ownership, or tenant rules to decide whether the authenticated caller can access a specific endpoint or perform a specific operation. If the caller is authenticated but lacks permission, the API usually returns `403 Forbidden`.
In API testing, both areas must be validated separately. Testers should verify successful authentication, missing credentials, invalid credentials, expired tokens, revoked tokens, and token tampering. They should also verify admin access, normal user access, guest access, role restrictions, resource ownership, cross-user access attempts, cross-tenant restrictions, and least privilege enforcement. A secure API must not only know who the caller is; it must also restrict what that caller can do.
Key Takeaway
Authentication proves identity. Authorization controls access. Authentication asks who the caller is, while authorization asks what the caller can do. Authentication happens first, and authorization follows. A missing or invalid token is usually a `401 Unauthorized` problem. A valid token without enough permission is usually a `403 Forbidden` problem.
For API testers, this distinction is practical, not theoretical. Use invalid credentials to test authentication failures. Use valid low-privilege credentials to test authorization failures. Test every important role, permission, scope, ownership rule, and tenant boundary. Strong authentication without strong authorization still leaves the API exposed. Strong authorization without reliable authentication cannot be trusted. Real API security requires both layers to work together.