Lesson 83 of 158 – API Security
83%

API Security

API security means protecting a REST API from unauthorized access, invalid requests, data theft, abuse, and common attacks. Since a mobile application communicates with the server through APIs, API security is an important part of mobile application development.

Note: API security is not one feature. It is a combination of HTTPS, authentication, authorization, validation, prepared statements, secure token handling, rate limiting, safe error responses, and other security practices.

1. What is API Security?

API security protects the communication and data exchanged between a client application and the server.

React Native
     ↓
 Secure Request
     ↓
 REST API
     ↓
 Authentication
     ↓
 Authorization
     ↓
 Validation
     ↓
 Database
     ↓
 Secure Response

2. Why is API Security Important?

A REST API can expose important application data. For example, a student management API may contain:

  • Student names
  • Email addresses
  • Mobile numbers
  • Course information
  • Payment information
  • Attendance information

The API must ensure that only authorized users can access protected information.

3. HTTPS

HTTPS encrypts communication between the mobile application and the server.

React Native
      ↓
     HTTPS
      ↓
    Server

Production APIs should use HTTPS rather than sending sensitive authentication information over plain HTTP.

4. Authentication

Authentication verifies who the user is.

Email
  +
Password
  ↓
Login API
  ↓
Verify Credentials
  ↓
JWT Token
  ↓
Authenticated User

JWT-based authentication can be used for protected REST APIs.

5. Authorization

Authorization determines what an authenticated user is allowed to do.

User Login
    ↓
Authentication
    ↓
Authorization
    ↓
Can User Perform This Action?

For example, a normal student may view their profile but should not be allowed to delete another student's record.

6. Authentication vs Authorization

Authentication Authorization
Who are you? What are you allowed to do?
Verifies identity Checks permissions
Login/token verification Role/permission checks

7. JWT Authentication

A JWT can be issued after successful login and then sent with protected API requests.

Login
  ↓
JWT
  ↓
React Native
  ↓
Authorization: Bearer JWT
  ↓
Protected API

8. Authorization Header

A common way to send a bearer token is through the Authorization header.

Authorization:
Bearer YOUR_JWT_TOKEN

The server can extract and verify the token before allowing access to protected resources.

9. Validate All Client Input

Data received from React Native should never be automatically trusted. The API should validate request data before processing it.

Request
   ↓
Validate
   ↓
Process
   ↓
Database

Validation should include required fields, data types, lengths, allowed values, and application-specific rules.

10. Use Prepared Statements

Prepared statements help protect database queries from SQL injection.

$stmt = $pdo->prepare(
    "SELECT *
     FROM users
     WHERE email = ?"
);

$stmt->execute([
    $email
]);

User-provided values should not be directly concatenated into SQL queries.

11. Avoid SQL Injection

Unsafe:

$sql =
    "SELECT *
     FROM users
     WHERE email = '$email'";

Safer:

$stmt = $pdo->prepare(
    "SELECT *
     FROM users
     WHERE email = ?"
);

$stmt->execute([
    $email
]);

12. Never Store Plain Passwords

Passwords should never be stored as plain text.

$hash = password_hash(
    $password,
    PASSWORD_DEFAULT
);

During login:

if (password_verify(
    $password,
    $hash
)) {

    // Login successful
}

13. Protect JWT Secrets

The JWT signing secret is sensitive server-side information.

Do not place the JWT secret inside the React Native application.

$secretKey =
    "YOUR_SERVER_SECRET";

In production, secrets should be managed securely rather than exposed in client-side code or public repositories.

14. Do Not Put Tokens in URLs

Authentication tokens should not normally be sent as URL query parameters.

Avoid:

/api/profile.php?token=YOUR_TOKEN

Prefer:

Authorization:
Bearer YOUR_TOKEN

URLs can appear in logs, browser history, analytics, and other systems, so sensitive credentials should not be placed in them.

15. Secure API Response

API responses should contain only information that the client actually needs.

Avoid returning:

password
password_hash
secret_key
internal_security_data

Return safe information:

{
    "id": 10,
    "name": "Rahul",
    "email": "rahul@example.com"
}

16. Safe Error Messages

Error responses should not expose sensitive server information.

Avoid:

{
    "error":
    "SQLSTATE[42S02]:
     Table 'library.users'
     doesn't exist..."
}

Prefer:

{
    "success": false,
    "message": "Server error"
}

Detailed technical errors can be logged securely on the server.

17. HTTP Status Codes

Use appropriate status codes for different security-related situations.

Status Meaning
200 Successful request
201 Resource created
400 Invalid request
401 Authentication required or invalid
403 Authenticated but not permitted
404 Resource not found
422 Validation failed
429 Too many requests
500 Server error

18. Rate Limiting

Rate limiting controls how frequently a client can call an API.

Client
  ↓
100 requests
  ↓
API Rate Limit
  ↓
Allow / Reject

Rate limiting can help reduce abuse, excessive traffic, and repeated automated requests.

19. Brute Force Protection

Login APIs should be protected against repeated password attempts.

Possible controls include:

  • Rate limiting
  • Temporary account restrictions
  • Monitoring failed login attempts
  • Strong passwords
  • Multi-factor authentication where appropriate

20. CORS

CORS stands for Cross-Origin Resource Sharing. It controls which web origins are allowed to make certain browser-based requests to an API.

For React Native applications, CORS generally does not work exactly like it does for browser-based web applications because native networking is not subject to the browser's same-origin policy in the same way.

Web Browser
    ↓
CORS Rules
    ↓
API

21. Access Control Headers

A web API may configure an appropriate CORS policy when browser clients need access.

header(
    "Access-Control-Allow-Origin: https://example.com"
);

Avoid allowing every origin in production unless that is intentionally required and understood.

22. Protect File Upload APIs

File upload endpoints require additional validation.

The API should consider:

  • Allowed file types
  • File size
  • File names
  • Storage location
  • Executable file risks

Never trust a client-provided file extension alone.

23. Token Expiration

JWT access tokens should generally have an expiration time.

$payload = [
    "sub" => $userId,
    "iat" => time(),
    "exp" => time() + 3600
];

The exp claim tells the server when the token should no longer be accepted.

24. Token Revocation

JWT access tokens are commonly designed to be stateless. If an application requires immediate invalidation before expiration, it can use a server-side revocation mechanism.

JWT
 ↓
Logout
 ↓
Revoke JTI
 ↓
Protected API
 ↓
Check Revocation
 ↓
Reject Revoked Token

This is especially useful when a user explicitly logs out or a token needs to be invalidated for security reasons.

25. Role-Based Authorization

Different users may have different permissions.

User
 ↓
JWT
 ↓
Role
 ↓
Permission Check
 ↓
API Resource

For example:

admin  → Add / Update / Delete
student → View Own Profile

26. Protect Database Credentials

Database credentials should remain on the server.

Never put this inside React Native:

$dbUser = "root";
$dbPassword = "database-password";

The mobile application should communicate with the REST API instead of connecting directly to the database.

React Native
     ↓
REST API
     ↓
MySQL

27. Logging and Monitoring

Server-side logs can help administrators detect errors and suspicious activity.

error_log(
    "API request failed"
);

Logs should not unnecessarily contain passwords, JWTs, or other sensitive credentials.

28. Secure React Native API Request

const response = await fetch(
    "https://example.com/api/profile.php",
    {
        method: "GET",

        headers: {
            "Accept":
                "application/json",
            "Authorization":
                "Bearer " + token
        }
    }
);

const result =
    await response.json();

The application should use HTTPS and securely manage the authentication token.

29. Complete API Security Flow

React Native
     ↓
HTTPS
     ↓
Authentication
     ↓
JWT Verification
     ↓
Authorization
     ↓
Input Validation
     ↓
Prepared SQL
     ↓
Database
     ↓
Safe JSON Response
     ↓
React Native

Additional protections can include rate limiting, logging, token expiration, revocation, secure file uploads, and role-based access control.

30. API Security Summary

A secure REST API validates incoming data, authenticates users, authorizes actions, protects database queries, uses HTTPS, handles tokens safely, and avoids exposing sensitive information.

HTTPS
  +
Authentication
  +
Authorization
  +
Validation
  +
Prepared Statements
  +
Safe Responses
  +
Rate Limiting
  +
Secure Tokens
  =
Better API Security

API security should be considered throughout the complete application, from the React Native interface to the PHP backend and database.

📌 Key Points

  • API security protects data and server resources.
  • Production APIs should use HTTPS.
  • Authentication verifies the identity of the user.
  • Authorization checks what the user is allowed to do.
  • JWTs can be used to authenticate protected API requests.
  • Never expose JWT secrets or database credentials in React Native.
  • Always validate data on the server.
  • Use prepared statements to reduce SQL injection risk.
  • Never store passwords as plain text.
  • Do not place authentication tokens in URLs.
  • Return only necessary and safe API data.
  • Do not expose detailed database or server errors to clients.
  • Rate limiting can help protect APIs from abuse.
  • JWT expiration and server-side revocation can improve token security.
  • Role-based authorization can restrict access to sensitive operations.
  • Secure file uploads require additional validation.
  • The next lesson will cover SQL injection prevention.

🧠 Quick Quiz

Question: Which practice helps protect a PHP API from SQL injection?