Popular Searches
Popular Course Categories
Popular Courses

Authentication Headers, Tokens, and API Security Basics

Authentication Headers, Tokens, and API Security Basics

API Integration and Network Requests

Authentication Headers, Tokens, and API Security Basics in React Native

Course: React Native Training

Topic: Authentication Headers, Tokens, and API Security Basics

Course Link: React Native Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to Authentication and API Security

Modern React Native applications frequently communicate with backend servers to retrieve user profiles, orders, messages, payment details, and other private information. These resources should not be accessible to every user. Authentication and API security help protect data by verifying a user's identity, checking permissions, and controlling access to protected endpoints.

When a user signs in, the backend may issue an access token. The React Native application can send this token in an HTTP request header when accessing protected API endpoints. The server validates the token and decides whether the requested operation is permitted.

Authentication must be implemented carefully because a mobile application runs on a device that the developer does not fully control. Application code, network requests, and locally stored data may be inspected or manipulated. Security checks must therefore be enforced by the backend, not only by the React Native interface.

Learning Objectives

  • Understand authentication, authorization, and API security.
  • Learn about HTTP request and response headers.
  • Understand access tokens, refresh tokens, and JWTs.
  • Send authentication headers using Fetch and Axios.
  • Implement a basic login and protected API request flow.
  • Understand token expiration, renewal, and logout.
  • Learn about secure token storage in React Native.
  • Understand HTTPS, OAuth 2.0, OpenID Connect, and PKCE.
  • Recognize common authentication vulnerabilities.
  • Apply security best practices to React Native projects.

2. What Is Authentication?

Authentication is the process of verifying the identity of a user or system. It answers the question: Who are you?

For example, when a user enters an email address and password into a mobile application, the backend verifies the credentials. If they are valid, the backend may create a session or issue authentication tokens.

Common Authentication Methods

Method Description Example
Password-based Verifies a username or email and password. Email and password login.
Token-based Uses a token issued after successful authentication. Bearer access token.
Multi-factor authentication Requires additional verification beyond one factor. Password plus authenticator code.
Biometric authentication Uses supported device biometrics to help verify the user locally. Face ID or fingerprint unlock.
OAuth 2.0 / OpenID Connect Uses standardized authorization and identity flows. Sign-in through an identity provider.

Biometric authentication on a device does not automatically prove the user's identity to a remote API. The application must still use an appropriate backend authentication or session mechanism when accessing protected server resources.

3. What Is Authorization?

Authorization determines what an authenticated user is allowed to access or do. It answers the question: What are you allowed to do?

For example, a customer may view their own orders, while an administrator may have permission to manage products. The backend must verify these permissions for each protected operation.

Authentication Authorization
Verifies identity. Verifies permissions.
Usually happens during sign-in or credential verification. Happens whenever a protected resource or operation is requested.
Example: verifying a login token. Example: checking whether the user can delete a product.

Important: Hiding a button in React Native is not sufficient authorization. A user may call the API directly. The backend must independently verify access rights.

4. Understanding HTTP Headers

HTTP headers provide additional information about a request or response. They communicate details such as the expected data format, authentication credentials, content type, and caching behavior.

Common HTTP Request Headers

Header Purpose Example
Authorization Sends authentication credentials or a token. Bearer ACCESS_TOKEN
Content-Type Indicates the format of the request body. application/json
Accept Indicates acceptable response formats. application/json
Cache-Control Provides caching directives. no-store
X-Request-ID May identify a request for troubleshooting. request-123

Example HTTP Request

GET /api/profile HTTP/1.1
Host: api.example.com
Authorization: Bearer ACCESS_TOKEN
Accept: application/json

The Authorization header carries the access token. The server validates the token and determines whether the requested profile can be returned.

5. What Is an Authentication Token?

An authentication token is a credential used to prove that a client has an authenticated session or has been granted particular access. A backend or identity provider typically issues the token after a successful authentication flow.

Tokens can allow the application to make subsequent requests without asking the user to enter their password every time. Tokens are sensitive credentials: if an attacker obtains a bearer token, they may be able to use it within its scope and validity period.

Typical Token-Based Authentication Flow

  1. The user enters their credentials into the application.
  2. The React Native application sends the credentials to the authentication endpoint over HTTPS.
  3. The backend verifies the credentials.
  4. The backend returns an access token and, depending on the design, a refresh token.
  5. The application stores or retains the tokens using an appropriate security strategy.
  6. The application sends the access token in the Authorization header for protected API requests.
  7. The backend validates the token and checks permissions.
  8. When the access token expires, the application may use a valid refresh token to obtain a new one.
  9. When the user logs out, the application clears local session data and invokes server-side session or token revocation when supported.

6. Types of Tokens

6.1 Access Token

An access token is a credential used to access protected resources. It is usually sent with each relevant API request.

Authorization: Bearer ACCESS_TOKEN

Access tokens should generally have a limited lifetime and only the permissions needed by the application.

6.2 Refresh Token

A refresh token is used to obtain a new access token when the existing access token expires or becomes invalid, according to the authentication system's rules.

Refresh tokens are often longer-lived and therefore require particularly careful storage and handling. Depending on the system, refresh tokens may rotate each time they are used and may be revoked when a user logs out or a suspicious session is detected.

6.3 ID Token

An ID token is commonly used in OpenID Connect to communicate information about an authenticated user to a client application. It is not interchangeable with an access token. Use access tokens for API access and ID tokens for their intended identity-related purpose.

6.4 Session Token

A session token or session identifier identifies a server-managed user session. The server may maintain session information and use the identifier to retrieve it. Session identifiers must be unpredictable and protected like other authentication credentials.

Token Type Main Purpose Typical Handling
Access token Access protected APIs. Send to the intended API in the authorization header.
Refresh token Obtain new access tokens. Keep in secure storage and follow the provider's renewal and rotation rules.
ID token Communicate identity claims in OpenID Connect. Validate according to the identity protocol; do not use as an API access token unless explicitly designed for that purpose.
Session token Identify a server-managed session. Protect it against disclosure, reuse, and session fixation.

7. Understanding the Authorization Header

The Authorization header is commonly used to send credentials to an API. The correct scheme depends on the API's authentication specification.

Bearer Token Example

Authorization: Bearer eyJhbGciOi...

In this example, Bearer identifies the authentication scheme and the value after it is the token. The example is abbreviated and is not a usable credential.

Why Use Bearer Tokens?

  • They are widely supported by HTTP APIs.
  • They allow authenticated requests without resending the user's password.
  • They can be configured with expiration times and limited permissions.
  • They can be revoked or rotated when the authentication system supports those features.

A bearer token does not prove which specific application is using it. Anyone possessing a valid token may be able to use it, so prevent token leakage and limit its scope, audience, and lifetime.

8. Sending Authentication Headers with Fetch

React Native includes the Fetch API, which can send HTTP requests with custom headers.

Example: GET Request with a Token

async function fetchProfile(accessToken) {
  const response = await fetch(
    "https://api.example.com/profile",
    {
      method: "GET",
      headers: {
        Authorization: `Bearer ${accessToken}`,
        Accept: "application/json"
      }
    }
  );

  if (response.status === 401) {
    throw new Error("Authentication required. Please sign in again.");
  }

  if (response.status === 403) {
    throw new Error("You do not have permission to access this resource.");
  }

  if (!response.ok) {
    throw new Error(`Request failed: ${response.status}`);
  }

  return response.json();
}

Explanation

  1. The function receives the access token from the application's authentication layer.
  2. The request includes the token in the Authorization header.
  3. The Accept header indicates that the client expects JSON.
  4. A 401 response is handled as an authentication problem.
  5. A 403 response is handled as an access-permission problem.
  6. Other unsuccessful responses are handled before parsing the JSON body.

Replace the example endpoint with the actual API URL and follow the authentication requirements documented by that API.

9. Sending Authentication Headers with Axios

Axios is an HTTP client that supports custom headers on individual requests and shared headers through configured instances.

Example: Authenticated Request

import axios from "axios";

async function fetchProfile(accessToken) {
  try {
    const response = await axios.get(
      "https://api.example.com/profile",
      {
        headers: {
          Authorization: `Bearer ${accessToken}`,
          Accept: "application/json"
        }
      }
    );

    return response.data;
  } catch (error) {
    if (error.response?.status === 401) {
      throw new Error("Authentication required.");
    }

    if (error.response?.status === 403) {
      throw new Error("Access denied.");
    }

    throw new Error("Unable to retrieve profile.");
  }
}

Why Use Axios?

  • It usually parses JSON responses automatically.
  • It supports request and response interceptors.
  • It provides convenient configuration for headers and timeouts.
  • It provides structured response and error information.
  • It supports reusable instances for API communication.

10. Creating a Reusable Axios API Client

Applications with multiple protected endpoints can use a shared Axios instance. This keeps the base URL and common request configuration in one place.

Example API Client

// src/services/apiClient.js
import axios from "axios";

export const apiClient = axios.create({
  baseURL: "https://api.example.com",
  timeout: 10000,
  headers: {
    Accept: "application/json"
  }
});

Using the Client

import { apiClient } from "./apiClient";

export async function getProfile(accessToken) {
  const response = await apiClient.get("/profile", {
    headers: {
      Authorization: `Bearer ${accessToken}`
    }
  });

  return response.data;
}

This example passes the token directly to the service method. In a larger application, the API client can obtain the current token through a well-defined authentication service or request interceptor. Avoid introducing circular dependencies between the API client and authentication state.

11. Adding Authentication with Axios Interceptors

An Axios request interceptor can attach an access token to outgoing requests. This reduces repeated header configuration across service methods.

Example with an Abstract Token Provider

// src/services/apiClient.js
import axios from "axios";
import { getAccessToken } from "./authTokenProvider";

export const apiClient = axios.create({
  baseURL: "https://api.example.com",
  timeout: 10000,
  headers: {
    Accept: "application/json"
  }
});

apiClient.interceptors.request.use(async config => {
  const accessToken = await getAccessToken();

  if (accessToken) {
    config.headers.Authorization = `Bearer ${accessToken}`;
  }

  return config;
});

getAccessToken() represents an application-specific function that returns the current access token. Implement this provider using your authentication architecture and secure storage strategy.

Important Considerations

  • Only attach tokens to requests intended for the appropriate trusted API.
  • Do not send an API token to unrelated third-party domains.
  • Ensure the token provider handles missing, expired, or cleared tokens.
  • Avoid registering duplicate interceptors every time a screen renders.
  • Provide a reliable way to remove interceptors if they are registered dynamically.
  • Do not log authorization headers or complete token values.

12. Understanding JSON Web Tokens (JWT)

JWT stands for JSON Web Token. It is a compact token format commonly used to transmit claims between parties. A signed JWT commonly contains three Base64URL-encoded parts separated by periods.

header.payload.signature

JWT Structure

Part Purpose
Header Contains token metadata, often including the signing algorithm and token type.
Payload Contains claims such as issuer, subject, expiration, and audience.
Signature Allows the receiving system to verify integrity and authenticity using the specified cryptographic method.

Common JWT Claims

  • iss: identifies the issuer.
  • sub: identifies the subject, often the user.
  • aud: identifies the intended audience.
  • exp: indicates the expiration time.
  • iat: indicates when the token was issued.
  • nbf: indicates when the token becomes valid.
  • jti: identifies the token, when included.

Security note: A signed JWT is not necessarily encrypted. Its header and payload can generally be decoded by anyone who obtains the token. Do not place passwords, private keys, or other confidential information in a JWT payload. The backend must verify the signature, issuer, audience, expiration, and other required claims rather than trusting decoded content alone.

13. Access Token Expiration and Refresh Flow

Access tokens should usually expire after a limited period. Expiration limits the time a stolen token can remain useful. The application must handle expired tokens without repeatedly asking users to sign in when a valid refresh flow is available.

Typical Refresh Process

  1. The application makes a protected API request using the current access token.
  2. The backend returns an authentication error because the token is expired or invalid.
  3. The application checks whether the authentication system supports token refresh.
  4. The application submits the refresh token to the designated token endpoint over HTTPS.
  5. The server validates the refresh token and applies any rotation or reuse-detection rules.
  6. If successful, the server returns a new access token and possibly a replacement refresh token.
  7. The application securely updates its stored credentials.
  8. The application retries the original request once using the new access token, when appropriate.
  9. If refresh fails, the application clears the local session and requires the user to authenticate again.

Refresh Security Rules

  • Do not refresh indefinitely after every error.
  • Do not treat every 401 response as proof that the access token expired; the request may contain other invalid credentials.
  • Retry the original request at most once as part of a controlled refresh flow.
  • Coordinate concurrent failed requests so they do not trigger many simultaneous refresh requests.
  • Follow the identity provider's refresh-token rotation and revocation requirements.
  • Never send refresh tokens to ordinary resource endpoints unless explicitly required by the protocol.

14. Securely Storing Tokens in React Native

React Native does not include a built-in secure credential store. The storage method should be chosen according to the sensitivity of the information and the application's security requirements.

Common Storage Options

Storage Method Typical Use Security Considerations
In-memory state Temporary access token storage. Usually disappears when the application process ends, but does not protect against every runtime attack.
AsyncStorage Non-sensitive settings and preferences. Unencrypted by default; do not use it for authentication tokens or secrets.
iOS Keychain Sensitive credentials and tokens. Platform-managed secure storage; configure accessibility according to requirements.
Android Keystore-backed storage Protecting cryptographic keys used by the application. Keys can be protected by the Android platform; use an appropriate library or implementation for token storage.
Expo SecureStore Small sensitive values in Expo applications. Uses platform-specific secure storage mechanisms; review platform behavior and limitations.
react-native-keychain Credentials and tokens in native React Native applications. Provides access to platform credential storage; review configuration and supported platform versions.

Install Expo SecureStore

npx expo install expo-secure-store

Example: Save and Retrieve a Token

import * as SecureStore from "expo-secure-store";

export async function saveAccessToken(token) {
  await SecureStore.setItemAsync("access_token", token);
}

export async function getAccessToken() {
  return await SecureStore.getItemAsync("access_token");
}

export async function removeAccessToken() {
  await SecureStore.deleteItemAsync("access_token");
}

This is a basic storage example for an Expo project. Native React Native projects can use an appropriate Keychain/Keystore-backed library. If the application uses refresh tokens, store them with a suitable secure-storage strategy as well.

Secure storage reduces exposure but does not make a compromised device or running application completely safe. Minimize how long sensitive values remain in memory and avoid leaking them through logs, analytics, crash reports, or persisted state.

15. Implementing a Login Request

A login screen collects credentials and submits them to an authentication endpoint. The backend verifies the credentials and returns the response defined by its API contract.

Example Login Service

export async function login(email, password) {
  const response = await fetch(
    "https://api.example.com/auth/login",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: JSON.stringify({ email, password })
    }
  );

  if (!response.ok) {
    throw new Error("Login failed. Check your credentials.");
  }

  const result = await response.json();

  if (typeof result.accessToken !== "string") {
    throw new Error("Invalid authentication response.");
  }

  return result;
}

The endpoint, request fields, error format, and response properties must match the actual backend. Some services return tokens using names such as access_token rather than accessToken.

Important Login Security Practices

  • Always send credentials over HTTPS.
  • Never log passwords or authentication responses containing tokens.
  • Do not store the user's password for automatic sign-in.
  • Use generic authentication failure messages when appropriate.
  • Apply server-side rate limiting and abuse prevention.
  • Follow the authentication provider's recommended login flow.
  • Use a standards-based identity flow rather than collecting third-party passwords in your application when using external identity providers.

16. Creating a Protected API Request

After a successful login, the application can use the access token to retrieve protected data.

Example Protected Request

export async function getOrders(accessToken) {
  const response = await fetch(
    "https://api.example.com/orders",
    {
      method: "GET",
      headers: {
        Authorization: `Bearer ${accessToken}`,
        Accept: "application/json"
      }
    }
  );

  if (response.status === 401) {
    throw new Error("Your session is no longer valid.");
  }

  if (response.status === 403) {
    throw new Error("You are not permitted to view these orders.");
  }

  if (!response.ok) {
    throw new Error("Unable to load orders.");
  }

  return response.json();
}

The server must verify the token and ensure that the user is permitted to access the requested orders. It must not rely on a user ID supplied by the mobile application without checking that the user has permission to access the corresponding records.

17. Implementing Logout Securely

Logout should end the user's local authenticated state and, where supported, invalidate the associated server-side session or refresh token. Simply navigating to the login screen is not sufficient if valid credentials remain stored.

Basic Logout Example

import * as SecureStore from "expo-secure-store";

export async function clearLocalSession() {
  await SecureStore.deleteItemAsync("access_token");
  await SecureStore.deleteItemAsync("refresh_token");
}

This example clears local tokens only. A production application should also call the identity provider's or backend's logout/revocation endpoint when available, clear relevant in-memory state and cached private data, and handle failures safely.

Logout Checklist

  • Clear locally stored access and refresh tokens.
  • Clear authenticated user state from React context or state management.
  • Remove cached private information where required.
  • Revoke or invalidate refresh tokens or server sessions when supported.
  • Prevent pending requests from repopulating private data after logout.
  • Return the user to an unauthenticated screen.

18. Understanding OAuth 2.0 and OpenID Connect

OAuth 2.0 is an authorization framework that allows an application to obtain limited access to protected resources. OpenID Connect (OIDC) adds an identity layer on top of OAuth 2.0 and defines a standard way to authenticate users and communicate identity information.

Common Terms

Term Meaning
Authorization server Issues tokens and handles authorization decisions.
Resource server Hosts protected API resources and validates access tokens.
Client The application requesting access.
Scope Describes the access requested or granted.
Redirect URI The destination to which the authorization server returns the authorization response.
PKCE Proof Key for Code Exchange, a security extension used with the authorization code flow.

Recommended Flow for Native Applications

For native mobile applications using an external identity provider, use the Authorization Code flow with PKCE when supported by the provider. Open the authentication page in the system browser or an appropriate secure browser session rather than collecting the identity provider's password inside an embedded WebView.

PKCE helps protect the authorization code from being intercepted and redeemed by another party. Register redirect URIs correctly and use verified app/universal links where supported. Never embed a confidential client secret in a distributed mobile application because application packages can be inspected.

19. HTTPS and Network Security

HTTPS protects data in transit using TLS. It helps prevent attackers on the network from reading or modifying traffic between the application and the server.

HTTP vs HTTPS

HTTP HTTPS
Does not provide TLS encryption for the connection. Uses TLS to protect data in transit.
Authentication credentials may be exposed on the network. Credentials and tokens are protected in transit when TLS is correctly configured.
Should not be used for sensitive production API traffic. Should be used for authentication and protected API requests.

Network Security Best Practices

  • Use HTTPS for every production API endpoint that carries sensitive information.
  • Never disable certificate validation to make a request succeed.
  • Use current TLS configurations on the server.
  • Do not include access tokens or passwords in URLs or query parameters.
  • Consider certificate pinning only when the threat model justifies it and the app has a reliable certificate/key rotation plan.
  • Test network behavior on real devices and supported operating systems.

20. API Keys vs Authentication Tokens

API keys and user authentication tokens serve different purposes. An API key often identifies an application, project, or calling service, while an access token typically represents an authorization grant or authenticated session.

Feature API Key Access Token
Typical purpose Identify or control access for an application or project. Authorize access to protected resources.
User identity Does not necessarily identify a specific user. May represent a user or another authorized subject.
Permissions Depends on the API's design and key restrictions. May have scopes, audience restrictions, and an expiration.
Mobile security A key embedded in a distributed app can be extracted. A stolen token can be used within its granted access and lifetime.

Do not assume an API key embedded in a React Native application is secret. If a provider requires a confidential key, route requests through a trusted backend instead of shipping the secret in the app. Public client identifiers may be appropriate for certain identity flows, but they are not substitutes for backend authorization.

21. Common Authentication and API Security Errors

Status Code Meaning Possible Action
400 Bad Request Check the request body, parameters, and API contract.
401 Unauthorized Check whether the token is missing, invalid, expired, or otherwise unacceptable.
403 Forbidden Check the user's permissions and the requested resource.
404 Not Found Verify the endpoint or resource identifier.
408 Request Timeout Check network conditions and retry policy.
429 Too Many Requests Respect rate limits and retry guidance.
500 Internal Server Error Investigate the backend and return a safe user-facing message.

Status codes are conventions, and individual APIs may use them differently. Read the backend's documentation and avoid exposing internal server details to users.

22. Common Security Vulnerabilities

22.1 Hardcoded Secrets

Placing private keys, confidential API credentials, or long-lived tokens in application source code exposes them to anyone who can inspect the application package.

Prevention: Keep confidential credentials on a trusted server and use a backend service to access protected resources.

22.2 Insecure Token Storage

Saving tokens in unencrypted persistent storage increases the risk of disclosure.

Prevention: Use platform-appropriate secure storage for sensitive credentials. Avoid storing tokens in AsyncStorage or persisted application state.

22.3 Missing Server-Side Authorization

An API may accept a request simply because the user is logged in, without checking whether the user is allowed to access the requested record.

Prevention: Verify ownership, roles, and permissions on every protected backend operation.

22.4 Token Leakage in Logs

Logging full request headers, authentication responses, or token values may expose credentials through debugging tools, analytics, or crash reports.

Prevention: Redact credentials from logs and telemetry. Log safe event identifiers rather than secrets.

22.5 Long-Lived Tokens

A token that remains valid for a long time may increase the impact of theft.

Prevention: Use appropriate expiration, limited scopes, secure refresh-token rotation, and revocation mechanisms where supported.

22.6 Insecure Deep Links

Deep links may be intercepted or invoked by other applications, depending on the platform and configuration. Including tokens or other secrets in deep-link URLs can expose them.

Prevention: Do not place sensitive tokens in deep links. Use verified links and the recommended OAuth redirect flow with PKCE when appropriate.

23. Managing Authentication State in React Native

Applications often use a context provider or another state management solution to keep track of whether the user is signed in. Authentication state may include the current user, loading status, and whether a valid session has been restored.

Example Authentication State

const initialAuthState = {
  user: null,
  isAuthenticated: false,
  isLoading: true
};

When the application starts, it may check secure storage for a saved credential and validate or refresh the session according to the backend's rules. While this check is in progress, show a loading screen instead of briefly displaying protected content.

Recommended State Design

  • Keep authentication state in a shared provider or a clearly defined state layer.
  • Keep token storage logic separate from UI components.
  • Do not persist passwords or sensitive credentials in ordinary application state storage.
  • Clear authenticated state after logout or failed session restoration.
  • Ensure protected screens do not treat client-side state as the final security authority.
  • Handle expired sessions and server-side revocation gracefully.

24. Handling Concurrent Token Refresh Requests

When multiple API requests fail because the access token has expired, each request may attempt to refresh the token. This can cause duplicate refresh requests or problems when the server rotates refresh tokens.

Recommended Strategy

  1. Detect an authentication error that is eligible for refresh.
  2. Check whether a refresh operation is already in progress.
  3. If no refresh is active, start one and let other failed requests wait for the same result.
  4. Update stored tokens atomically according to the provider's rotation rules.
  5. Retry eligible original requests once with the new access token.
  6. If refresh fails, clear the session and request a new login.

Implement this flow centrally in the API client or authentication service rather than duplicating it across every screen. Make sure refresh requests do not trigger the same interceptor recursively.

25. API Security Best Practices Checklist

  • Use HTTPS for all sensitive network communication.
  • Send access tokens in the appropriate authorization header.
  • Never send tokens or passwords in URL query parameters.
  • Keep confidential API secrets on the server.
  • Store sensitive tokens using platform-appropriate secure storage.
  • Use short-lived access tokens when suitable for the application's threat model.
  • Protect refresh tokens and follow rotation and revocation rules.
  • Validate token signatures, issuer, audience, expiration, and required claims on the server.
  • Enforce authorization on every protected backend operation.
  • Apply rate limits and abuse prevention to authentication endpoints.
  • Use generic error messages that do not expose internal implementation details.
  • Redact credentials from logs, analytics, and crash reports.
  • Keep dependencies updated and review third-party packages.
  • Implement a reliable logout and session-expiration process.
  • Use OAuth Authorization Code with PKCE for native applications when using a compatible external identity provider.
  • Test unauthorized access, expired tokens, revoked sessions, and permission failures.

26. Practical Project: Secure User Profile App

Project Goal: Build a React Native application that allows users to sign in, store authentication credentials securely, access a protected profile endpoint, handle session expiration, and log out safely.

Project Requirements

  1. Create a login screen with email and password fields.
  2. Send credentials to a test backend over HTTPS.
  3. Validate the login response and handle unsuccessful authentication.
  4. Store tokens using a suitable secure-storage solution.
  5. Create a reusable API client.
  6. Attach the access token using the Authorization header.
  7. Fetch and display the user's profile from a protected endpoint.
  8. Display loading, success, and error states.
  9. Handle 401 and 403 responses appropriately.
  10. Implement the refresh-token flow if supported by the backend.
  11. Clear local authentication state during logout.
  12. Invoke server-side logout or token revocation when supported.
  13. Verify that tokens and passwords never appear in logs.
  14. Test requests with missing, invalid, expired, and revoked tokens.

Suggested Project Structure

src/
  components/
    LoadingIndicator.js
  context/
    AuthContext.js
  screens/
    LoginScreen.js
    ProfileScreen.js
  services/
    apiClient.js
    authService.js
    profileService.js
    secureTokenStorage.js

Expected Result

A user can sign in and access their own protected profile. The application handles invalid credentials, expired sessions, network failures, and logout without exposing authentication secrets. The backend remains responsible for validating credentials, verifying tokens, and enforcing permissions.

27. Practice Exercises

  1. Create a Fetch request that includes a bearer token in its authorization header.
  2. Implement the same protected request using Axios.
  3. Create a reusable Axios instance with a base URL and timeout.
  4. Build a login service that validates the returned token format.
  5. Store and retrieve a test token using Expo SecureStore.
  6. Handle a 401 response separately from a 403 response.
  7. Build a logout function that clears local session data.
  8. Design a refresh-token flow with a single controlled retry.
  9. Explain why AsyncStorage should not be used for authentication tokens.
  10. Identify sensitive values that must be removed from application logs.
  11. Explain the difference between access tokens, refresh tokens, and ID tokens.
  12. Write a security checklist for a React Native login screen.

28. Interview Questions and Answers

Q1. What is authentication?

Answer: Authentication verifies the identity of a user or system before granting access to an application or resource.

Q2. What is authorization?

Answer: Authorization determines which resources or operations an authenticated user is allowed to access.

Q3. What is an HTTP Authorization header?

Answer: It is a request header used to provide authentication credentials, such as a bearer access token.

Q4. What is a bearer token?

Answer: A bearer token is a credential that grants access to whoever possesses it, within its scope and validity. It must be protected from disclosure.

Q5. What is the difference between an access token and a refresh token?

Answer: An access token is used to access protected resources. A refresh token is used to obtain a new access token according to the authentication provider's rules.

Q6. What is JWT?

Answer: JSON Web Token is a compact token format used to transmit claims. A signed JWT provides integrity protection but is not necessarily encrypted.

Q7. Why should tokens not be stored in AsyncStorage?

Answer: AsyncStorage is unencrypted by default. Sensitive credentials should be stored using appropriate platform secure-storage mechanisms.

Q8. What is the difference between 401 and 403?

Answer: A 401 response indicates that valid authentication credentials are missing or unacceptable. A 403 response generally indicates that the request is understood but access is not permitted.

Q9. What is HTTPS?

Answer: HTTPS uses TLS to protect data in transit between a client and a server.

Q10. What is OAuth 2.0?

Answer: OAuth 2.0 is an authorization framework that enables clients to obtain limited access to protected resources.

Q11. What is OpenID Connect?

Answer: OpenID Connect is an identity layer built on OAuth 2.0 that defines a standard way for clients to authenticate users and obtain identity information.

Q12. What is PKCE?

Answer: Proof Key for Code Exchange is an extension to the authorization code flow that helps prevent intercepted authorization codes from being redeemed by an unauthorized party.

Q13. Why should a mobile app not contain a confidential API secret?

Answer: The application package can be inspected, so embedded secrets can be extracted. Confidential credentials should remain on a trusted backend.

Q14. What should happen when an access token expires?

Answer: If a valid refresh flow is supported, the application can obtain a new access token and retry an eligible request once. If refresh fails, it should clear the session and require authentication again.

Q15. Why is server-side authorization important?

Answer: Client-side checks can be bypassed. The backend must independently verify ownership, roles, and permissions before returning data or performing protected operations.

29. Quick Revision Notes

  • Authentication verifies identity; authorization checks permissions.
  • HTTP headers carry metadata and authentication credentials.
  • The Authorization header commonly carries a bearer access token.
  • Access tokens are used for protected API access.
  • Refresh tokens are used to obtain new access tokens when supported.
  • ID tokens are intended for identity information in OpenID Connect.
  • JWT payloads are not automatically encrypted.
  • Fetch and Axios can both send authenticated HTTP requests.
  • Use platform-appropriate secure storage for sensitive tokens.
  • Never ship confidential API secrets inside a mobile application.
  • Use HTTPS and never disable certificate validation to bypass errors.
  • Handle token expiration, refresh, revocation, and logout carefully.
  • Enforce all important permissions on the backend.
  • OAuth 2.0 with Authorization Code and PKCE is commonly recommended for native app authorization flows.
  • Never log passwords, full tokens, or sensitive authentication responses.

30. Conclusion

Authentication headers, tokens, and API security are essential topics for building reliable React Native applications. Developers should understand how tokens are issued, how authorization headers are attached to requests, how sessions are restored and ended, and how expired credentials are handled.

A secure application combines HTTPS, appropriate token storage, limited token lifetimes, careful refresh handling, safe logging, and strong backend authorization. No client-side technique alone can guarantee security; the mobile application and backend must work together to protect users and their data.

31. Useful Resources

whatsapp