Broken Authentication

Introduction

Authentication is the first line of defense for protected APIs. Before an API allows a caller to view data, create a record, update a profile, transfer money, download a report, or perform an administrative action, it must know who is making the request. Authentication answers that identity question. It verifies whether the caller is a legitimate user, application, service, device, or integration.

Broken Authentication occurs when that identity verification is weak, incomplete, incorrectly implemented, or bypassable. If authentication is broken, attackers may impersonate valid users, steal accounts, reuse stolen tokens, bypass login, access protected resources, or trigger sensitive workflows without proper identity proof. Because authentication sits before most other API protections, failure at this layer can lead to widespread compromise.

Broken Authentication is one of the critical risks highlighted in the OWASP API Security Top 10. It is especially important in API testing because APIs are often called directly by clients, mobile apps, partner systems, automation tools, and attackers. A browser screen may hide protected actions, but API endpoints can still be called with Postman, curl, REST Assured, custom scripts, or intercepted mobile traffic. Therefore, the API must enforce authentication consistently on the server side.

For testers, Broken Authentication is not only about checking whether valid login works. A strong test strategy must also verify invalid login, missing credentials, weak credentials, expired tokens, revoked tokens, malformed tokens, incorrect token signatures, session timeout, logout behavior, password reset security, repeated failed login attempts, and multi-factor authentication where it exists. A secure authentication flow must accept legitimate identity proof and reject everything else.

What Is Broken Authentication?

Broken Authentication is a security vulnerability where weaknesses in the authentication process allow attackers to bypass identity checks or impersonate legitimate users. The weakness may exist in the login flow, token generation, token validation, password policy, session management, API key handling, password reset process, or account recovery flow. The common problem is that the API trusts a caller who should not be trusted.

A simple definition is this: Broken Authentication happens when an API fails to properly verify who the caller is. If a protected endpoint returns data without requiring credentials, authentication is broken. If the API accepts an invalid token, authentication is broken. If an expired token still works, authentication is broken. If an attacker can change a JWT payload and become admin because the API does not verify the signature, authentication is broken.

Authentication should not be confused with authorization. Authentication verifies identity. Authorization verifies permission. Authentication asks, "Who are you?" Authorization asks, "What are you allowed to do?" Broken Authentication affects the first question. If the system cannot reliably identify the caller, permission checks become unreliable because they are based on a false or unverified identity.

Why Authentication Is Important

Authentication ensures that only legitimate users and applications can access protected APIs. It protects private data, business operations, personal information, financial workflows, and administrative functions. Without authentication, anyone who knows an endpoint URL may call it. That may be acceptable for public content, but it is unacceptable for private accounts, employee records, payment actions, medical records, customer orders, or internal reports.

Authentication also creates accountability. If the system knows which user or application made a request, actions can be audited. Logs can show who logged in, who changed data, who downloaded a report, or who attempted a restricted action. Without reliable authentication, audit trails lose value because requests cannot be tied to a trusted identity.

In modern systems, authentication is also part of trust between services. A microservice may call another service using a client credential, signed token, API key, or mutual TLS certificate. If service authentication is weak, attackers or compromised systems may call internal APIs directly. API authentication must cover both human users and machine clients.

Authentication Workflow

A typical API authentication workflow starts when the client sends credentials or identity proof to an authentication service. The service validates the credentials, checks account status, applies security rules, and issues an access token or session if authentication succeeds. The client then sends that token to protected APIs. Each protected API validates the token before processing the request.

Client
  |
Login Request
  |
Authentication Server
  |
Credentials Verified
  |
Access Token Issued
  |
Protected API

If any step in this workflow is weak, attackers may exploit the process. If login allows unlimited guesses, brute-force attacks become easier. If tokens are predictable, attackers may generate valid-looking tokens. If the API does not validate token expiration, old stolen tokens remain useful. If the API trusts the JWT payload without verifying the signature, attackers can change claims. If logout does not revoke or invalidate relevant sessions, users may remain exposed after sign-out.

Common Causes of Broken Authentication

Broken Authentication can appear for many reasons. One common cause is missing authentication on protected endpoints. A developer may create an endpoint for testing, internal use, or a new feature and forget to apply the authentication middleware. If the endpoint returns protected data to anonymous callers, it is a serious vulnerability.

Weak password policies are another cause. If the system allows simple passwords such as `123456`, `password`, or `admin`, attackers can guess credentials more easily. Poor password policies become worse when there is no rate limiting, no account lockout, no monitoring, and no multi-factor authentication for sensitive accounts.

Invalid token validation is a frequent API issue. APIs may fail to validate JWT signatures, issuer, audience, expiration, not-before time, token type, scopes, or revocation status. A token should not be accepted because it is present or because its payload looks correct. It must be cryptographically valid and appropriate for the API being called.

Session management weaknesses can also create Broken Authentication. Predictable session IDs, long-lived sessions, missing session expiration, insecure cookies, missing logout invalidation, and session fixation vulnerabilities can allow attackers to reuse or steal sessions. In APIs, token theft and poor token storage create similar risks.

Insecure password reset and account recovery flows are another common source. If an attacker can reset a password by guessing an OTP, intercepting a reset token, reusing an expired link, or answering weak recovery questions, the login form may be strong but account takeover is still possible. Authentication includes the entire identity lifecycle, not only the primary login endpoint.

Example: Missing Authentication

Consider an endpoint that returns employee data:

GET /employees

HTTP/1.1 200 OK

If this endpoint returns protected employee data without any credentials, authentication is missing. Anyone who discovers the URL can access sensitive information. A secure API should require identity proof before returning private employee records. The expected response for a missing token is commonly `401 Unauthorized`.

GET /employees

HTTP/1.1 401 Unauthorized

Testing for missing authentication is straightforward but important. Testers should call protected endpoints with no Authorization header, no cookies, no API key, and no session information. Protected endpoints should reject anonymous calls consistently. Public endpoints should be documented clearly so there is no confusion about which APIs are intentionally open.

Example: Weak Passwords

Weak passwords make account compromise easier. If an administrator account uses username `admin` and password `123456`, attackers do not need a sophisticated exploit. They can guess the credential, use common password lists, or attempt credential stuffing from leaked data. Password weaknesses are especially risky for high-privilege accounts.

A good password policy should discourage common passwords, require appropriate length, and support secure storage using strong password hashing algorithms such as bcrypt, Argon2, or PBKDF2. Passwords should never be stored in plaintext or reversible encryption. Even strong passwords should be protected by rate limiting, suspicious login monitoring, and multi-factor authentication where appropriate.

Testers can verify that weak passwords are rejected during registration, reset, and change-password flows. They can also verify that repeated failed login attempts trigger throttling, temporary lockout, additional verification, or another documented security response. The goal is to make guessing credentials expensive and detectable.

Example: Invalid Token Accepted

Token validation is central to API authentication. A protected request often includes an Authorization header:

Authorization: Bearer invalidToken123

If the API accepts this invalid token and returns protected data, authentication is broken. The expected response is commonly `401 Unauthorized`. The API should validate the token's signature, issuer, audience, expiration, format, and any required claims. A token that is malformed, unsigned, signed with the wrong key, expired, revoked, or intended for another audience should not be accepted.

JWT validation deserves special attention. JWT payloads are readable by design. Attackers can decode and modify payload values such as role, user ID, or expiration. The API must verify the token signature to detect tampering. Trusting the payload without signature validation allows attackers to create their own identity or elevate privileges.

{
  "sub": "101",
  "role": "Admin",
  "exp": 1893456000
}

The values inside the token are meaningful only if the token is trusted. If an attacker can change `role` to `Admin` and the API accepts it, authentication and authorization are both compromised.

Example: Expired Token Accepted

Access tokens should not work forever. If an expired access token still returns `200 OK`, the API is accepting identity proof that should no longer be valid. This increases the impact of token theft because stolen tokens remain useful for too long. Short-lived tokens limit exposure by reducing the useful lifetime of compromised credentials.

Expired Access Token
  |
Protected API
  |
HTTP/1.1 401 Unauthorized

Testers should create or obtain expired tokens and verify that APIs reject them. They should also test not-before claims, revoked tokens, disabled users, password-change invalidation, logout behavior, and refresh token handling where applicable. A secure system should have a clear token lifecycle: issue, use, expire, refresh, revoke, and reject.

Common Authentication Attacks

A brute-force attack attempts many username and password combinations until one succeeds. This is often automated. Rate limiting, account lockout, adaptive risk checks, and monitoring help reduce the risk. Testers should verify that repeated failures are not allowed indefinitely.

Credential stuffing uses usernames and passwords leaked from other websites. Since many users reuse passwords, attackers try known credential pairs against the API. Password spraying is similar, but it tries one common password against many accounts to avoid triggering user-specific lockouts too quickly. Both attacks show why password policy, monitoring, and MFA matter.

Session hijacking happens when an attacker steals or obtains a valid session or token and uses it to impersonate the user. Token theft can happen through insecure storage, logs, URLs, browser vulnerabilities, compromised devices, or network exposure when HTTPS is not enforced. Once stolen, a token may allow API access until it expires or is revoked.

Authentication bypass attacks attempt to access protected resources without completing the expected login flow. This may involve missing middleware, alternate endpoints, debug routes, misconfigured gateways, weak API keys, predictable session IDs, or flaws in identity provider integration. Testers should not assume that one protected route means all similar routes are protected.

Authentication vs Authorization

AreaAuthenticationAuthorization
Main questionWho are you?What are you allowed to do?
PurposeVerify identityVerify permissions
OccursFirstAfter authentication
Common failureInvalid token acceptedEmployee accesses admin function
Common status401 Unauthorized403 Forbidden

This distinction matters in testing. If a request has no valid identity, the issue is authentication and the response is commonly `401 Unauthorized`. If the caller is authenticated but lacks permission, the issue is authorization and the response is commonly `403 Forbidden`. Mixing these concepts can create weak test coverage and unclear defects.

Broken Authentication Risks

Broken Authentication can lead to account takeover, unauthorized access, data breaches, identity theft, financial fraud, privilege escalation, and compliance violations. If attackers can impersonate users, they may read private data, change account settings, submit transactions, download reports, or move laterally through connected systems.

The impact is higher when high-privilege accounts are compromised. An admin account may manage users, permissions, data exports, system configuration, billing, or integrations. A service account may access internal APIs at scale. A compromised token may allow automated data extraction. Because APIs are scriptable, attackers can abuse broken authentication quickly once a weakness is found.

Broken Authentication in API Testing

API testers should verify both successful and failed authentication paths. Valid credentials should work as expected. Invalid passwords, invalid usernames, missing credentials, malformed credentials, missing tokens, invalid tokens, expired tokens, revoked tokens, modified JWTs, and disabled accounts should be rejected. Authentication tests should cover every protected endpoint class, not only the login API.

Password policy testing should include short passwords, common passwords, reused passwords if the system checks history, invalid reset tokens, expired reset links, repeated reset attempts, and account recovery edge cases. Session testing should include timeout behavior, logout behavior, token reuse after logout, refresh token behavior, and concurrent sessions if relevant. MFA testing should include missing codes, wrong codes, expired codes, reused codes, backup codes, and trusted-device behavior where implemented.

Authentication testing should also inspect response safety. A login failure should not reveal whether the username exists if the system intentionally avoids account enumeration. Error responses should not expose stack traces, database errors, token secrets, password policy internals, or identity provider details. Logs should not store plaintext passwords or full tokens.

Example Test Cases

A valid credentials test confirms that legitimate users can log in and receive the expected token or session. The expected status may be `200 OK`, and the response may include an access token, refresh token, expiration, user profile summary, or other contract-defined fields.

An invalid password test confirms that a wrong password is rejected with `401 Unauthorized` or another documented authentication failure. An invalid username test should also fail safely. A missing token test calls a protected endpoint without the Authorization header and expects denial. An expired token test confirms that old access tokens no longer work. A modified JWT test changes payload values and verifies that the API rejects the token because the signature is no longer valid.

A repeated failed login test checks brute-force protection. After several failed attempts, the system may slow responses, return `429 Too Many Requests`, require additional verification, temporarily lock the account, or log a security event. The expected behavior depends on the design, but unlimited rapid guessing should not be allowed for sensitive accounts.

REST Assured Example

REST Assured can validate positive and negative authentication scenarios in Java API automation. A basic authentication success case may look like this:

given()
    .auth()
    .preemptive()
    .basic("admin", "password123")
.when()
    .get("/employees")
.then()
    .statusCode(200);

The matching negative case should prove that wrong credentials are rejected:

given()
    .auth()
    .preemptive()
    .basic("admin", "wrongPassword")
.when()
    .get("/employees")
.then()
    .statusCode(401);

For bearer-token APIs, REST Assured tests should include valid, missing, invalid, expired, and modified tokens. These tests should be separated clearly so a failure tells the team which authentication rule failed.

Postman Example

Postman is useful for exploring authentication behavior because testers can quickly switch environment variables and headers. A security-focused collection can include requests for missing Authorization header, invalid token, expired token, wrong username and password, revoked token, disabled user, weak password, reset token reuse, and repeated failed login attempts.

Postman tests can assert status codes, absence of protected data, response schema, and safe error messages. Environments should be handled carefully. Real passwords, API keys, and tokens should not be exported or committed to source control. If shared collections are needed, sensitive variables should be excluded or managed through a secure secret-management process.

Karate Example

Karate can express authentication tests in a readable form. A valid token request may look like this:

Given header Authorization = 'Bearer ' + validToken
When method GET
Then status 200

A negative test can use an invalid token and verify `401 Unauthorized`:

Given header Authorization = 'Bearer invalidToken'
When method GET
Then status 401

Karate also works well for data-driven authentication checks. Testers can run the same protected endpoint with missing token, expired token, malformed token, modified token, revoked token, and valid token. The scenario names should remain clear so the report communicates the exact authentication rule under test.

Real-World Examples

In banking, Broken Authentication can allow attackers to view account balances, transfer funds, add beneficiaries, download statements, or access customer information. Even a short-lived authentication defect can have serious financial consequences because attackers can automate transactions quickly.

In healthcare, broken authentication may expose patient medical records, prescriptions, insurance data, lab reports, and appointment information. Healthcare systems often have strict privacy and compliance requirements, so identity verification must be reliable and auditable.

In e-commerce, attackers may take over customer accounts, view saved addresses, place fraudulent orders, redeem loyalty points, access saved payment references, or change delivery information. Credential stuffing is especially relevant because customers often reuse passwords across sites.

In enterprise applications, compromised administrator accounts can expose confidential company data, modify user permissions, download reports, configure integrations, or create additional privileged users. Service account compromise can also be severe because service credentials may have broad API access.

Best Practices

Use strong authentication mechanisms that match the risk of the API. Enforce secure password policies, require HTTPS for all authentication requests, use short-lived access tokens, validate JWT signatures, validate issuer and audience, implement token expiration, support revocation where needed, and protect refresh tokens carefully. Enable multi-factor authentication for sensitive users and high-risk operations.

Rate-limit login attempts and protect against credential stuffing, password spraying, and brute-force attacks. Lock accounts temporarily or add additional verification after repeated failures according to the security design. Store passwords using strong one-way password hashing algorithms such as bcrypt, Argon2, or PBKDF2 with proper salts and work factors. Never store plaintext passwords.

Keep credentials out of logs, URLs, analytics events, screenshots, and exported test files. Do not return full tokens in error messages. Do not trust client-provided identity fields. Protected APIs should derive identity from trusted authentication mechanisms, not from request body values such as `userId` unless the request is separately authorized and validated.

Common Mistakes

A common mistake is accepting invalid tokens. APIs must validate token signatures, expiration, issuer, audience, and required claims before granting access. Another mistake is allowing weak password policies that make compromise easier. Password controls should be combined with monitoring and rate limits because even strong passwords can be attacked.

No account lockout or throttling is another major issue. Unlimited login attempts give attackers room to brute-force credentials. Long-lived tokens are also risky because stolen credentials remain useful for too long. Access tokens should have limited lifetimes, and refresh tokens should be protected and revocable.

Logging sensitive credentials is especially dangerous. Passwords, API keys, full tokens, OTP values, and reset links should not appear in application logs, test reports, CI logs, or browser console output. Once secrets are logged, many people and systems may be able to see them.

Common HTTP Status Codes

ScenarioCommon Status Code
Successful login200 OK
Invalid credentials401 Unauthorized
Missing authentication401 Unauthorized
Expired token401 Unauthorized
Authenticated but insufficient permissions403 Forbidden
Too many login attempts429 Too Many Requests or temporary lockout response

Status codes should follow the API contract. The key testing point is consistency. Authentication failures should not accidentally return protected data. Authorization failures should not be confused with authentication success. Rate-limit behavior should be documented and verifiable.

Practical Review Checklist

When reviewing authentication, start by identifying all protected endpoints. Call each protected endpoint without credentials and verify denial. Then call endpoints with invalid, malformed, expired, revoked, and modified credentials. Confirm that tokens are validated completely and that errors do not leak secrets.

Review login and account flows. Are weak passwords rejected? Are repeated failed attempts throttled or locked? Are password reset links single-use and time-limited? Are reset tokens protected? Does logout behave as expected? Are disabled users blocked? Is MFA enforced where required?

Review operational behavior. Are failed logins logged safely? Are suspicious patterns monitored? Are credentials omitted from logs and reports? Are API keys and tokens rotated when needed? Are secrets stored outside source code? Authentication is strongest when implementation, testing, monitoring, and credential management work together.

Building a Practical Authentication Test Strategy

A practical authentication test strategy should start with risk, not only with endpoint count. Login, token refresh, password reset, account recovery, admin access, service-to-service access, and high-value customer flows deserve deeper validation than low-risk public endpoints. Testers should identify which authentication mechanisms are used by the application and then create focused checks for each mechanism. A system may use username and password for users, OAuth for delegated access, API keys for partner applications, and client credentials for internal services. Each mechanism has different failure modes.

The test suite should include baseline positive tests so the team knows legitimate users can access the system. It should also include negative tests that prove the API rejects unsafe identity proof. Missing token, invalid token, expired token, wrong token type, wrong issuer, wrong audience, modified JWT payload, disabled user, revoked session, and password reset token reuse are all valuable checks. These tests should run repeatedly because authentication behavior can break when gateways, identity providers, application middleware, or token libraries are changed.

Authentication tests should avoid depending on one shared admin account for everything. Shared high-privilege credentials hide many problems and create maintenance risk. It is better to maintain controlled test identities for common roles and states: active user, locked user, disabled user, expired password user, MFA-enabled user, lower-privilege user, and service client. This makes the test results clearer and reduces the chance that one credential change breaks the entire suite.

Test data handling is also part of the strategy. Passwords, API keys, tokens, and reset links must not be written into source code, screenshots, console output, exported Postman files, or CI logs. Test credentials should be stored through secure configuration or secret-management tools. When reports are generated, they should show the scenario outcome without exposing sensitive values. A test suite that validates authentication but leaks tokens in its own output creates a different security problem.

Finally, authentication testing should be connected to monitoring expectations. If repeated failed login attempts occur, the system should produce a useful audit signal. If a revoked token is used, the event may need to be logged. If a high-privilege account fails MFA repeatedly, security teams may need visibility. Testers may not own production monitoring, but they can confirm that authentication events are observable in lower environments and that failures are handled safely. This closes the gap between test automation and real-world security operations.

Interview Questions

A common interview question is: what is Broken Authentication? A strong answer is that Broken Authentication is a security vulnerability where flaws in the authentication process allow attackers to bypass identity verification or impersonate legitimate users. It can happen because of missing authentication, weak passwords, invalid token validation, poor session handling, insecure password reset, or weak protection against brute-force attacks.

Another question is: what are common causes of Broken Authentication? Examples include weak passwords, missing authentication, weak API keys, predictable session IDs, invalid JWT validation, missing token expiration, credential reuse, credential stuffing, brute-force vulnerabilities, insecure password reset, and poor session management.

Interviewers may ask what API testers should verify. A good answer includes valid login, invalid login, missing credentials, invalid credentials, expired tokens, revoked tokens, JWT signature validation, password policy, session timeout, logout behavior, account lockout, password reset security, MFA where applicable, and safe error responses.

Another common question is which HTTP status code is typically returned for authentication failures. The common answer is `401 Unauthorized`. If the caller is authenticated but lacks permission, the common answer is `403 Forbidden`. This distinction shows that the candidate understands authentication and authorization separately.

Interview-Ready Explanation

Broken Authentication is a security vulnerability where weaknesses in the authentication process allow attackers to bypass login or impersonate legitimate users. It can result from missing authentication checks, weak password policies, invalid or expired tokens being accepted, poor session management, predictable session IDs, insecure password reset flows, inadequate protection against brute-force attacks, or incorrect JWT validation. Because authentication verifies identity, failure at this layer can expose protected APIs and lead to account takeover, unauthorized access, and data breaches.

In API testing, Broken Authentication should be validated with both positive and negative scenarios. Testers should verify successful login, invalid passwords, invalid usernames, missing tokens, invalid tokens, expired tokens, revoked tokens, modified JWT payloads, token signature validation, session timeout, logout behavior, account lockout, password reset security, and MFA where implemented. Authentication failures should commonly return `401 Unauthorized`, and the API should never return protected data for unauthenticated requests.

Broken Authentication can be prevented through strong authentication mechanisms, secure password storage, HTTPS, short-lived tokens, complete JWT validation, token expiration and revocation, rate limiting, account lockout, MFA for sensitive access, secure session management, safe error handling, and regular security testing. A secure API accepts only valid identity proof and rejects missing, invalid, expired, tampered, or unsafe credentials consistently.

Key Takeaway

Broken Authentication is one of the most serious API security risks because identity is the foundation for every protected request. If an API cannot reliably verify who is calling, attackers may impersonate users, steal accounts, access sensitive data, or abuse business functions. Authentication must be enforced at the API layer, not assumed from the user interface.

For testers, the practical rule is simple: test valid identity and invalid identity with equal seriousness. Confirm that legitimate users can authenticate, but also confirm that missing credentials, wrong credentials, expired tokens, modified tokens, revoked tokens, weak passwords, repeated login failures, and insecure recovery flows are handled safely. Strong Broken Authentication testing gives real confidence that protected APIs are not open to unauthorized callers.