Lesson 69 of 158 – Authentication Concept
69%

Authentication Concept

Authentication is one of the most important concepts in a REST API. It is used to verify the identity of a user before allowing access to protected resources. In this lesson, we will understand authentication, authorization, login, tokens, protected APIs, and how authentication works in a React Native mobile application.

Note: Authentication answers the question "Who are you?" Authorization answers the question "What are you allowed to do?"

1. What is Authentication?

Authentication is the process of verifying the identity of a user.

User
 ↓
Email + Password
 ↓
Authentication API
 ↓
Verify Identity
 ↓
Authenticated User

For example, when a user logs into a mobile application, the application needs to verify that the supplied credentials belong to a valid account.

2. Why Authentication is Needed

Without authentication, anyone who knows an API URL could potentially attempt to access protected resources.

  • Protect user accounts.
  • Protect private information.
  • Protect student records.
  • Restrict access to private APIs.
  • Identify the current user.
  • Provide secure access to application features.

3. Authentication vs Authorization

Authentication Authorization
Verifies identity Checks permissions
Who are you? What can you access?
Usually happens during login Usually happens after identity is verified
Example: Verify password Example: Check admin permission

4. Authentication Flow

React Native
     ↓
Login Request
     ↓
PHP Authentication API
     ↓
Find User
     ↓
Verify Password
     ↓
Authentication Successful
     ↓
Token
     ↓
React Native

After successful authentication, the server can issue a token that the mobile application can use for later protected API requests.

5. Login is Part of Authentication

The login process is commonly used to authenticate a user.

Email
   +
Password
   ↓
Login API
   ↓
Find User
   ↓
password_verify()
   ↓
Authentication Result

A successful login can then lead to token-based authentication.

6. Credentials

Credentials are information used to prove a user's identity.

Common examples include:

  • Email and password
  • Username and password
  • Access tokens
  • API keys

For a typical user login API, email and password are used as the initial credentials.

7. Password Authentication

In password-based authentication, the user provides a password and the server verifies it against the stored password hash.

Entered Password
       ↓
password_verify()
       ↓
Stored Password Hash
       ↓
Match?
  ┌────┴────┐
 Yes       No
  ↓          ↓
Success    Reject

8. Password Hashing and Authentication

During registration, the password is hashed before it is stored. During login, the entered password is verified against the stored hash.

Registration

Password
   ↓
password_hash()
   ↓
Database


Login

Password
   ↓
password_verify()
   ↓
Database Hash

9. What Happens After Login?

A simple login response can tell the application that authentication was successful.

{
    "success": true,
    "message": "Login successful"
}

For mobile applications, a token is commonly returned so that subsequent requests can prove the authenticated user's identity.

10. What is a Token?

A token is a value that a client can send with later API requests to represent an authenticated session or identity.

Login
  ↓
Server verifies user
  ↓
Token generated
  ↓
Mobile App stores token
  ↓
Token sent with protected requests

11. Why Use Tokens?

Tokens allow a mobile application to authenticate later API requests without sending the user's password with every request.

  • Useful for mobile applications.
  • Can be sent with protected API requests.
  • Reduce the need to repeatedly send credentials.
  • Can represent an authenticated user.
  • Can be designed with expiration and other security controls.

12. Authentication Token Flow

LOGIN

Email + Password
       ↓
Authentication API
       ↓
Verify Credentials
       ↓
Generate Token
       ↓
Return Token


PROTECTED API

Mobile App
       ↓
Token
       ↓
Protected API
       ↓
Verify Token
       ↓
Allow / Reject

13. Protected API

A protected API is an endpoint that requires authentication before returning protected information or performing a protected operation.

GET /api/profile.php

Authorization required
        ↓
Verify Token
        ↓
Valid?
   ┌────┴────┐
  Yes       No
   ↓          ↓
Return     401
Data       Error

14. Authorization Header

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

Authorization: Bearer YOUR_TOKEN

The server can read this header and verify the supplied token.

15. Bearer Authentication

Bearer authentication means the client presents a token as proof that it has authenticated access.

Authorization:
Bearer abc123...

The exact token format depends on the authentication system being used.

16. Read Authorization Header in PHP

The Authorization header can be obtained from the incoming HTTP request. The exact PHP server environment can affect how headers are exposed.

$authorization =
    $_SERVER['HTTP_AUTHORIZATION'] ?? '';

if ($authorization === '') {

    http_response_code(401);

    echo json_encode([
        "success" => false,
        "message" => "Authentication required"
    ]);

    exit;
}

17. Extract Bearer Token

If the application uses the Bearer scheme, the token can be extracted from the Authorization header.

$authorization =
    $_SERVER['HTTP_AUTHORIZATION'] ?? '';

if (
    !preg_match(
        '/Bearer\s+(.+)/i',
        $authorization,
        $matches
    )
) {

    http_response_code(401);

    echo json_encode([
        "success" => false,
        "message" => "Invalid authorization header"
    ]);

    exit;
}

$token = trim($matches[1]);

18. Authentication Middleware Concept

Authentication checking can be placed in a reusable middleware or helper so that multiple protected APIs do not need to repeat the same code.

Request
   ↓
Authentication Check
   ↓
Valid?
 ┌─┴─┐
No  Yes
↓    ↓
401  API Logic

19. Authentication Failure

When authentication fails, the API can return HTTP 401.

http_response_code(401);

echo json_encode([
    "success" => false,
    "message" => "Authentication required"
]);

20. Authentication vs Permission

Authentication and authorization should be treated as separate steps.

User Request
     ↓
Authenticated?
     ↓
Yes
     ↓
Check Permission
     ↓
Allowed?
 ┌───┴───┐
Yes     No
 ↓       ↓
Allow   403

A valid login does not automatically mean the user can access every operation.

21. Example: Admin API

Suppose an API is available only to administrators.

Authentication
      ↓
Identify User
      ↓
Check Role
      ↓
Admin?
 ┌────┴────┐
Yes       No
 ↓          ↓
Allow      403

Authentication identifies the user. Authorization checks whether that user has the required role.

22. Authentication in React Native

A React Native application commonly has a login screen that communicates with the authentication API.

Login Screen
     ↓
Email + Password
     ↓
POST /login
     ↓
Authentication API
     ↓
Token
     ↓
Mobile App

23. Send Token from React Native

After login, the token can be sent with a protected API request.

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

        headers: {
            "Authorization":
                "Bearer " + token
        }
    }
)
.then(response => response.json())
.then(data => {

    console.log(data);

});

24. Token Storage Concept

A mobile application needs a suitable mechanism for retaining authentication state between requests and, when appropriate, across app launches.

Login
 ↓
Receive Token
 ↓
Securely Store Token
 ↓
Read Token
 ↓
Send Token
 ↓
Protected API

The next lessons will cover token authentication and later secure mobile token storage.

25. Authentication with HTTPS

Login credentials and authentication tokens should be transmitted over HTTPS in a real application.

React Native
      ↓
    HTTPS
      ↓
Authentication API
      ↓
    HTTPS
      ↓
React Native

HTTPS helps protect data while it travels between the mobile application and the server.

26. Authentication Security Rules

  • Never store plain-text passwords.
  • Use password_hash() during registration.
  • Use password_verify() during login.
  • Use HTTPS for authentication requests.
  • Do not return passwords or password hashes.
  • Protect sensitive API endpoints.
  • Validate authentication tokens on protected requests.
  • Use authorization checks for restricted operations.
  • Use suitable token expiration and revocation strategies.

27. Authentication Architecture

React Native
      ↓
 Login Screen
      ↓
POST /login
      ↓
PHP Authentication API
      ↓
MySQL Users
      ↓
password_verify()
      ↓
Token Authentication
      ↓
Protected API
      ↓
Authorization
      ↓
JSON Response

28. Complete Authentication Concept Example

<?php

header("Content-Type: application/json");

$email = $data['email'] ?? '';
$password = $data['password'] ?? '';

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

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

$user = $stmt->fetch(
    PDO::FETCH_ASSOC
);

if (
    !$user ||
    !password_verify(
        $password,
        $user['password']
    )
) {

    http_response_code(401);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid email or password"
    ]);

    exit;
}

/*
    Authentication succeeded.

    A token can now be generated
    and returned to the mobile app.
*/

echo json_encode([
    "success" => true,
    "message" => "Authentication successful"
]);

?>

29. Authentication Best Practices

  • Authenticate users before allowing access to protected resources.
  • Hash passwords securely.
  • Verify passwords using password_verify().
  • Use HTTPS.
  • Use tokens for subsequent authenticated API requests.
  • Do not expose passwords or password hashes.
  • Return suitable HTTP status codes.
  • Keep authentication and authorization logic separate.
  • Protect admin-only operations with authorization checks.
  • Use secure token storage on mobile applications.
  • Handle expired or invalid tokens properly.

30. Authentication Concept Summary

Authentication verifies the identity of a user. In a mobile application, the user usually logs in with an email and password. The PHP API finds the user and verifies the password hash. After successful authentication, the server can provide a token that the mobile application sends with future protected API requests.

Registration
     ↓
Password Hash
     ↓
Database
     ↓
Login
     ↓
password_verify()
     ↓
Authentication
     ↓
Token
     ↓
Protected API
     ↓
Authorization

📌 Key Points

  • Authentication verifies the identity of a user.
  • Authorization determines what an authenticated user is allowed to do.
  • Login is commonly used to authenticate users.
  • Passwords should be hashed during registration.
  • password_verify() should be used during login.
  • Tokens can be used for subsequent authenticated API requests.
  • Protected APIs require authentication before providing protected resources.
  • Bearer tokens can be sent using the Authorization header.
  • HTTP 401 can be returned when authentication is missing or invalid.
  • HTTP 403 can be used when an authenticated user is not permitted to perform an operation.
  • React Native can send authentication tokens with Fetch or Axios.
  • Authentication and authorization should be handled separately.
  • HTTPS should be used for login and protected API communication.
  • Passwords and password hashes should never be returned to the mobile application.
  • The next step is learning token-based authentication.

🧠 Quick Quiz

Question: What is the main purpose of authentication?