A REST API can expose valuable data and business operations, so authentication and abuse prevention should be part of its design from the beginning. For PHP applications, a secure API commonly combines API keys, JSON Web Tokens (JWTs), rate limiting, strict input validation, and consistent authorization rules.
These controls solve different problems. An API key can identify an application or integration. A JWT can authenticate a user or service across multiple requests without storing a session on the server. Rate limiting helps reduce brute-force attempts, scraping, denial-of-service pressure, and accidental overload. None of these mechanisms is sufficient on its own, but together they create a stronger security boundary.
Start with HTTPS and a secure request model
Before implementing authentication, require HTTPS for every API request. API keys, bearer tokens, passwords, and personal data must not travel over plain HTTP. Redirecting HTTP traffic is not enough for sensitive APIs; configure the application and infrastructure so that authenticated requests are accepted only over TLS.
Use a predictable request model, such as:
- Authentication: determine who or what is making the request.
- Authorization: determine whether that identity may perform the requested action.
- Validation: verify that the request contains acceptable data.
- Abuse prevention: limit repeated or suspicious activity.
- Auditing: record enough information to investigate security events without logging secrets.
Keep these responsibilities separate. A valid token should not automatically grant access to every resource, and a rate limit should not replace authorization.
Use API keys for application identification
API keys are useful when you need to identify a client application, partner integration, internal service, or command-line tool. They are usually long, random values sent in a header such as X-API-Key. Avoid placing keys in URLs because query strings can appear in browser history, proxy logs, analytics systems, and server logs.
GET /api/orders HTTP/1.1
Host: example.com
X-API-Key: your-key-value
Store only a hash of each API key in the database. If the database is compromised, hashed keys are more difficult to use immediately than plaintext credentials. Generate keys with a cryptographically secure random source, such as PHP's random_bytes(), and encode them with bin2hex() or a URL-safe encoding.
$plainKey = bin2hex(random_bytes(32));
$keyHash = hash('sha256', $plainKey);
// Store $keyHash, not $plainKey.
// Show $plainKey to the owner only once.
When a request arrives, hash the submitted key and look up the hash. If you use a comparison operation for values that may be compared in memory, prefer a constant-time comparison such as hash_equals(). More importantly, define clear key lifecycle controls:
- Assign each key an owner, purpose, status, and creation date.
- Support immediate revocation and scheduled expiration.
- Allow key rotation without interrupting every integration.
- Give different clients different keys so one compromise does not affect all clients.
- Apply permissions, such as read-only or access to a specific resource group.
API keys are often bearer credentials: anyone who possesses one may use it. They are therefore not a replacement for user authorization, and they should not be embedded in public JavaScript applications or mobile apps where extraction is difficult to prevent.
Authenticate users with short-lived JWTs
JWTs are signed tokens that can carry claims about an authenticated subject. A common pattern is to issue an access token after a successful login and require it in the Authorization header:
Authorization: Bearer eyJ...
A JWT normally contains a header, a payload, and a signature. The signature helps the API verify that the token was issued by a trusted authority and was not modified. It does not encrypt the payload, so do not place passwords, secrets, or sensitive personal information inside it.
Validate all important claims, including:
issto confirm the trusted issuer.audto confirm the intended API.expto reject expired tokens.nbfandiatwhen your design uses them.subto identify the user or service.- The signing algorithm, using an allowlist rather than accepting whatever the token declares.
Use a maintained JWT library rather than implementing token parsing and signature verification from scratch. Keep access tokens short-lived, and use a carefully designed refresh-token flow when users need longer sessions. Refresh tokens should be stored and transmitted more carefully than ordinary access tokens, rotated where appropriate, and revoked after suspicious activity or logout.
A JWT proves that a token was signed by a trusted issuer; it does not prove that the caller is allowed to access every record. After validation, enforce resource-level authorization. For example, a user with a valid token should not be able to request another user's invoice simply by changing an ID in the URL.
Combine API keys and JWTs deliberately
Some APIs require both credentials. For example, an API key may identify a partner application while a JWT identifies the end user. This allows you to apply limits and permissions at two levels:
- The API key determines which application is making the request.
- The JWT determines which user or service is authenticated.
- Authorization rules confirm that the application may act for that user or access that operation.
Do not add multiple credentials simply because more headers appear more secure. Define what each credential means, which endpoints require it, and how failures are handled. A public endpoint may require only a key, while a user-specific endpoint may require both a key and a bearer token.
Implement rate limiting at the right boundaries
Rate limiting restricts how many requests a client can make during a period. Apply limits based on the threat and business operation, not only on IP address. Useful dimensions include API key, authenticated user, IP address, route, and sometimes a combination of these values.
For example, a login endpoint may need a strict limit, while a read-only catalog endpoint can allow more traffic. Password reset, token issuance, search, file upload, and expensive reporting routes deserve special attention.
Common algorithms include fixed windows, sliding windows, token buckets, and leaky buckets. A shared store such as Redis is often appropriate when the API runs on multiple PHP workers or servers. A local in-memory counter can produce inconsistent results across instances.
When a client exceeds a limit, respond with HTTP status 429 Too Many Requests. Include a Retry-After header when you can calculate a useful retry interval. Keep the response generic so it does not reveal internal infrastructure or whether a particular account exists.
HTTP/1.1 429 Too Many Requests
Retry-After: 30
Content-Type: application/json
{"error":"rate_limit_exceeded"}
Rate limiting is not a complete denial-of-service defense. Put network-level protections, a reverse proxy, a web application firewall, or managed infrastructure in front of the PHP application when the risk and traffic justify it.
Validate input and prevent common PHP API vulnerabilities
Authentication does not make unsafe input safe. Validate request bodies against an expected schema, reject unknown or unexpected fields where practical, and apply type, length, format, and range checks. Use prepared statements for database queries, never concatenate user input into SQL, and encode output according to its context.
For JSON requests, verify the content type and handle parsing errors explicitly:
$data = json_decode(file_get_contents('php://input'), true);
if (!is_array($data) || json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['error' => 'invalid_json']);
exit;
}
Also configure sensible request and upload limits. Protect against mass assignment by copying only fields that the current operation is allowed to change. Never allow a client to submit privileged fields such as an account role, ownership ID, or verification status unless a separate administrative rule permits it.
Protect secrets and make failures consistent
Keep signing keys, database passwords, and API-key management credentials outside source control. Use environment-specific secret storage with controlled access, and rotate secrets according to your risk model. If a signing key is compromised, have a plan for key rotation and token invalidation.
Return consistent authentication errors without confirming whether a username, API key, or account exists. Detailed diagnostic information belongs in protected server logs, not in responses sent to untrusted clients. Logs should include timestamps, route, status, request correlation ID, and a privacy-conscious client identifier, but never raw passwords, API keys, JWTs, or refresh tokens.
Test the security design
Security controls should be tested as API behavior, not only as isolated functions. Include tests for expired and tampered JWTs, wrong issuers and audiences, revoked API keys, missing credentials, insufficient permissions, malformed JSON, oversized requests, repeated login attempts, and cross-user resource access.
Review whether sensitive data can appear in logs, whether error responses disclose account existence, and whether rate limits work consistently across all application instances. Dependency updates, secret rotation drills, and periodic access reviews are part of maintaining the API after launch.
A practical defense-in-depth checklist
- Require HTTPS and disable insecure access to protected routes.
- Hash API keys at rest and provide revocation, expiration, and rotation.
- Use a trusted JWT library and validate signature, algorithm, issuer, audience, and time claims.
- Keep access tokens short-lived and protect refresh tokens.
- Enforce authorization at the resource and action level.
- Rate-limit authentication, expensive, and abuse-prone endpoints.
- Validate JSON, query parameters, path variables, and uploads.
- Use prepared database statements and allowlists for writable fields.
- Keep secrets out of source control and logs.
- Monitor failures and test the controls continuously.
A secure PHP REST API is built from layered controls rather than a single authentication method. API keys provide accountable application identification, JWTs support stateless user authentication, and rate limiting reduces abuse. When these measures are combined with HTTPS, strict authorization, careful validation, secret management, and meaningful monitoring, your API becomes substantially harder to misuse and easier to operate safely.