APIs are the backbone of modern applications and web services. However, if they are not secured properly, your API endpoints can be accessed by unauthorized websites, apps, or even bots. This can result in data leaks, misuse, spam, and unauthorized automation.

In this article, we’ll explore practical techniques with code examples. These techniques will help protect your API from being misused. They cover both GET and POST requests. Hackers or content thieves just find the simplest method to find the data lake. So, for this, you have to keep yourself protected.

The Problem: Open API Endpoints

If your API is publicly hosted (e.g., on https://api.thbd.in), anyone can send GET or POST requests to it. This includes:

So, how can we limit API usage only to your app or website? Solutions to Restrict API Access

1 Use API Key Validation

Add a secret API key that your own app or frontend sends with every call.

Why?

Ensures that only clients who know the key can use the API.
Prevents casual access from external sources.

How?

PHP Example (server-side):

// Secure value you generate and use in your frontend/app
$expected_api_key = 'my_super_secret_key';
$api_key = $_GET['api_key'] ?? $_POST['api_key'] ?? '';
if ($api_key !== $expected_api_key) {
    http_response_code(403);
    echo json_encode(['error' => 'Forbidden - Invalid API Key']);
    exit;
}

Frontend (JavaScript or Android):

fetch("https://api.thbd.com/data?api_key=my_super_secret_key")

Note: Keep the key secret. Avoid exposing it in frontend JS if possible.

2 Use CORS Headers (for Web APIs)

CORS (Cross-Origin Resource Sharing) is a mechanism that tells browsers which domains are allowed to access your API.

Why?

Stops other websites from using JavaScript to call your API.
Enforced by the browser, not foolproof but useful.

Example (PHP):

$allowed_origins = ['https://thbd.in'];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowed_origins)) {
    header("Access-Control-Allow-Origin: $origin");
} else {
    http_response_code(403);
    echo json_encode(['error' => 'CORS Forbidden']);
    exit;
}

Note: CORS doesn’t protect against backend (e.g., curl, Postman) misuse. Combine it with other techniques.

3 Verify User Agent or Custom Headers

You can confirm requests by checking the User-Agent or custom headers sent by your app.

Example (PHP):

$expected_ua = 'MyAppAgent/1.0'; 
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
if ($user_agent !== $expected_ua) {
    http_response_code(403);
    echo json_encode(['error' => 'Invalid client']);
    exit;
}

Or set a custom header:

$custom_header = $_SERVER['HTTP_X_MY_SECRET'] ?? '';
if ($custom_header !== 'secret_value') {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

Note: Don’t rely solely on User-Agent; it can be spoofed. But it’s helpful as an extra layer.

4 Check Referrer (for Web only)

You can restrict requests coming from your domain only.

Example:

$referrer = $_SERVER['HTTP_REFERER'] ?? '';
if (strpos($referrer, 'thbd.in') === false) {
    http_response_code(403);
    echo json_encode(['error' => 'Invalid referrer']);
    exit;
}

Note: Referrers can be faked or omitted, so use this only as an additional check.

5 JWT Authentication (Advanced Users)

Use JSON Web Tokens (JWT) to confirm sessions and users.

Why?

Ensures that each request is tied to a valid user. Tokens can expire or be revoked. It can’t be easily faked.

Example:

On login, generate JWT.

Send it with every API call in the Authorization: Bearer <token> header.
Check the token on the server before processing.

Note: Ideal for full app auth systems. More complex, but very secure.

6 Rate Limiting and IP Blacklisting

Implement demand rate limits per IP or token.

Why?

Prevents brute force and abuse. Slows down attackers.

Example (PHP Basic IP Blocking):

$ip = $_SERVER['REMOTE_ADDR'];
$blocked_ips = ['192.168.1.100'];
if (in_array($ip, $blocked_ips)) {
    http_response_code(403);
    echo json_encode(['error' => 'Access blocked']);
    exit;
}

Note: Use Redis or a database for tracking requests per IP and timing them.

Best Practice: Combine Multiple Layers

No single method is 100% secure. The best protection comes from layering:

Prevent your API from being hit by unauthorized apps, bots, or websites, Protection Works for Bypass Risk Use Case.
API Key is used by all platforms. It has a medium risk and provides basic authentication.
CORS is used by browsers for JavaScript and web APIs and has a low risk. JWT Tokens are used by apps for user sessions and have a very low risk. Referrers are used by browsers for an additional check and have a medium risk. Rate Limiting is used by all to provide low-risk abuse protection.
Referrer Browsers Medium Additional check Rate Limiting All Low Abuse protection.

Conclusion

Use multiple techniques for maximum security. Never expose sensitive endpoints without proper checks.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply