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.
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.
Without authentication, anyone who knows an API URL could potentially attempt to access protected resources.
| 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 |
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.
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.
Credentials are information used to prove a user's identity.
Common examples include:
For a typical user login API, email and password are used as the initial credentials.
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
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
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.
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
Tokens allow a mobile application to authenticate later API requests without sending the user's password with every request.
LOGIN
Email + Password
↓
Authentication API
↓
Verify Credentials
↓
Generate Token
↓
Return Token
PROTECTED API
Mobile App
↓
Token
↓
Protected API
↓
Verify Token
↓
Allow / Reject
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
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.
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.
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;
}
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]);
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
When authentication fails, the API can return HTTP 401.
http_response_code(401);
echo json_encode([
"success" => false,
"message" => "Authentication required"
]);
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.
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.
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
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);
});
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.
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.
React Native
↓
Login Screen
↓
POST /login
↓
PHP Authentication API
↓
MySQL Users
↓
password_verify()
↓
Token Authentication
↓
Protected API
↓
Authorization
↓
JSON Response
<?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"
]);
?>
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
Question: What is the main purpose of authentication?