Lesson 71 of 158 – JWT Introduction
71%

JWT Introduction

JWT stands for JSON Web Token. It is a popular token format used for authentication between a client application and a server. JWT is especially useful when building REST APIs for mobile applications such as React Native.

Note: JWT allows the server to create a signed token containing claims about the authenticated user. The client can send the JWT with later protected API requests.

1. What is JWT?

JWT means JSON Web Token. It is a compact format for representing information between two parties as a JSON-based token.

In REST API authentication, JWT can be issued after successful login and then sent with protected API requests.

Login
  ↓
Verify User
  ↓
Create JWT
  ↓
Send JWT
  ↓
Mobile App
  ↓
Protected API
  ↓
Verify JWT

2. Why Use JWT?

JWT is commonly used for API authentication because the token can carry claims and can be verified using a cryptographic signature.

  • Useful for REST APIs.
  • Works well with mobile applications.
  • Can contain user-related claims.
  • Can include an expiration time.
  • Can be verified by the server.
  • Does not require the password to be sent with every request.

3. JWT Authentication Flow

React Native
     ↓
Email + Password
     ↓
Login API
     ↓
Verify Credentials
     ↓
Create JWT
     ↓
Return JWT
     ↓
React Native
     ↓
Store JWT
     ↓
Protected API
     ↓
Send JWT
     ↓
Verify JWT
     ↓
Return Data

4. JWT Structure

A JWT normally contains three parts separated by dots.

HEADER.PAYLOAD.SIGNATURE

The three parts are:

  • Header
  • Payload
  • Signature

For example, a JWT has a structure similar to:

xxxxx.yyyyy.zzzzz

5. JWT Header

The header contains information about the token, such as the token type and signing algorithm.

{
    "alg": "HS256",
    "typ": "JWT"
}

The alg field specifies the signing algorithm and typ identifies the token type.

6. JWT Payload

The payload contains claims. Claims are pieces of information about the token or the subject of the token.

{
    "user_id": 101,
    "email": "user@example.com"
}

Applications can also use registered claims such as iss, sub, aud, exp, and iat.

7. JWT Signature

The signature is used to verify that the token was created by a trusted party and has not been modified after it was signed.

Header
   +
Payload
   +
Secret / Private Key
   ↓
Signature

The exact signing method depends on the selected JWT algorithm.

8. Complete JWT Structure

JWT
│
├── Header
│   ├── alg
│   └── typ
│
├── Payload
│   ├── user_id
│   ├── email
│   └── exp
│
└── Signature

These three encoded sections are joined using dots.

Header.Payload.Signature

9. JWT is Base64URL Encoded

The header and payload of a JWT are encoded using Base64URL. The resulting token is designed to be safely transmitted as text.

Encoding is not the same as encryption.

Important: Do not put passwords, secret keys, or other sensitive information inside the JWT payload merely because the payload is encoded. The payload can generally be decoded by the client.

10. JWT Example

A JWT may look like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJ1c2VyX2lkIjoxMDEsImV4cCI6MTczMDAwMDAwMH0
.
signature-value

The actual token is normally represented as one line with the three parts separated by dots.

11. JWT Claims

Claims are statements about the token or its subject.

{
    "sub": "101",
    "name": "Rahul",
    "role": "student",
    "iat": 1730000000,
    "exp": 1730003600
}

The claims included in a JWT should be limited to information that the application actually needs.

12. Registered JWT Claims

Claim Meaning
iss Issuer
sub Subject
aud Audience
exp Expiration time
nbf Not valid before
iat Issued at
jti JWT ID

13. The exp Claim

The exp claim represents the expiration time of the JWT.

{
    "user_id": 101,
    "exp": 1730003600
}

After the token expires, the API should reject it according to the authentication rules of the application.

14. The iat Claim

The iat claim represents the time at which the token was issued.

{
    "user_id": 101,
    "iat": 1730000000
}

JWT timestamps are commonly represented as Unix time values.

15. The sub Claim

The sub claim identifies the subject of the token. For a user authentication system, it can represent the authenticated user.

{
    "sub": "101"
}

16. JWT Signing Algorithms

JWT can use different signing algorithms.

Algorithm Family Example
HMAC HS256
RSA RS256
ECDSA ES256

The choice depends on the architecture and security requirements of the application.

17. HS256

HS256 is an HMAC-based signing algorithm using SHA-256. It uses a shared secret to create and verify the signature.

Header
   +
Payload
   +
Shared Secret
   ↓
HS256
   ↓
Signature

The secret must be kept securely on the server.

18. JWT Secret Key

A secret key is used by algorithms such as HS256 to sign and verify tokens.

$secretKey =
    "CHANGE_THIS_TO_A_SECURE_SECRET";
Important: Never expose a JWT secret key to the React Native application, browser client, Git repository, or public source code.

19. JWT Verification

When a protected API receives a JWT, the server verifies the token's signature and checks relevant claims such as expiration.

JWT
 ↓
Read Header
 ↓
Read Payload
 ↓
Verify Signature
 ↓
Check Claims
 ↓
Valid?
 ┌──┴──┐
Yes    No
 ↓      ↓
Allow  401

20. JWT is Not Encryption

A signed JWT provides integrity and authenticity when properly verified. It does not automatically hide the payload contents.

JWT Payload
     ↓
Base64URL Decode
     ↓
Readable JSON
Remember: Do not store passwords, private keys, or other confidential secrets in a normal JWT payload.

21. JWT with REST API

JWT can be used to protect REST API endpoints.

POST /api/login.php
        ↓
      JWT
        ↓
GET /api/profile.php
        ↓
Authorization: Bearer JWT
        ↓
Verify JWT
        ↓
Return Profile

22. JWT with React Native

React Native can receive a JWT after successful login and then send it with requests to protected APIs.

React Native
      ↓
POST Login
      ↓
PHP API
      ↓
JWT
      ↓
React Native
      ↓
Protected Request
      ↓
Authorization: Bearer JWT

23. Send JWT using Fetch

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

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

const data =
    await response.json();

console.log(data);

24. JWT Login Response

A login API can return a JWT in its JSON response.

{
    "success": true,
    "message": "Login successful",
    "token": "eyJhbGciOiJIUzI1NiIs..."
}

The mobile application can then use the returned token for authenticated requests.

25. JWT Authorization Header

A JWT can be sent in the Authorization header using the Bearer scheme.

GET /api/profile.php

Authorization:
Bearer eyJhbGciOiJIUzI1NiIs...

The server should validate the JWT before providing protected data.

26. JWT Security Rules

  • Keep signing keys secret.
  • Use HTTPS.
  • Do not store passwords in JWT payloads.
  • Do not put JWTs in URLs.
  • Validate the signature.
  • Check expiration when applicable.
  • Use an appropriate signing algorithm.
  • Keep token lifetime appropriate for the application.
  • Protect token storage on mobile devices.
  • Do not trust JWT claims without verifying the token.

27. JWT vs Simple Random Token

Random Token JWT
Usually opaque Contains structured claims
Server may need token storage Can carry claims inside the token
Meaning usually comes from server-side data Claims can be read after decoding
Implementation depends on database/session design Uses a standardized token structure

Both approaches can be useful. The appropriate choice depends on the application architecture and security requirements.

28. JWT Concept Example

{
    "header": {
        "alg": "HS256",
        "typ": "JWT"
    },

    "payload": {
        "sub": "101",
        "role": "student",
        "iat": 1730000000,
        "exp": 1730003600
    },

    "signature": "SIGNED_VALUE"
}

The real JWT combines these parts into a compact token:

HEADER.PAYLOAD.SIGNATURE

29. JWT in a Mobile Application

              React Native
                   │
                   ▼
             Login Screen
                   │
                   ▼
             Login API
                   │
                   ▼
          Verify Email/Password
                   │
                   ▼
               Create JWT
                   │
                   ▼
             Return JWT
                   │
                   ▼
          Store Token Securely
                   │
                   ▼
          Protected API Request
                   │
                   ▼
        Authorization: Bearer JWT
                   │
                   ▼
             Verify JWT
                   │
                   ▼
              JSON Data

30. JWT Introduction Summary

JWT is a standardized token format commonly used for authentication in REST APIs. A JWT normally contains a header, payload, and signature. After successful login, a server can issue a JWT. The React Native application can then send the JWT with protected API requests using the Authorization header.

JWT
│
├── Header
│
├── Payload
│
└── Signature

Login
  ↓
Create JWT
  ↓
React Native
  ↓
Bearer JWT
  ↓
Protected API
  ↓
Verify JWT
  ↓
Return Data

📌 Key Points

  • JWT stands for JSON Web Token.
  • JWT is commonly used for authentication in REST APIs.
  • A JWT normally contains Header, Payload, and Signature.
  • The header contains token type and signing algorithm information.
  • The payload contains claims.
  • The signature helps verify token integrity and authenticity.
  • JWT payload data is encoded, not automatically encrypted.
  • Passwords and secret keys should not be stored in the JWT payload.
  • The exp claim can represent token expiration.
  • The iat claim represents the issued-at time.
  • The sub claim identifies the subject of the token.
  • HS256 is an HMAC-based JWT signing algorithm.
  • Signing secrets must remain on the server.
  • JWTs can be sent using the Authorization Bearer header.
  • React Native can use JWTs to access protected REST APIs.
  • The next lesson will cover creating a JWT login API.

🧠 Quick Quiz

Question: What are the three main parts of a JWT?