### **What is JWT (JSON Web Token)?** JWT (**JSON Web Token**) is a secure, compact, and self-contained way to transmit information between two parties as a **JSON object**. It is commonly used for **authentication and authorization** in web applications. --- ### **🔹 Structure of JWT** A JWT consists of three parts, separated by dots (`.`): ``` header.payload.signature ``` Example JWT: ``` eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsInJvbGUiOiJ1c2VyIiwiaWF0IjoxNjk4MDAwMDB9.4E9XgD7qPoU5ogRmC4wsh4oSejKbLJ9XxJfE34hHlGc ``` Each part has a specific role: 1️⃣ **Header** - Specifies the type of token (`JWT`) and signing algorithm (`HS256`, `RS256`). ```json { "alg": "HS256", "typ": "JWT" } ``` 2️⃣ **Payload (Claims)** - Contains the data (user information, permissions, etc.). - Example: ```json { "user_id": 123, "role": "user", "iat": 1698000000 } ``` 3️⃣ **Signature** - Ensures the token has not been tampered with. - Generated using a **secret key** or **private key** (if using asymmetric encryption). --- ### **🔹 How JWT Works in Authentication** 1️⃣ **User Logs In** → Sends credentials (email & password). 2️⃣ **Server Generates JWT** → Signs it using a secret key. 3️⃣ **JWT is Sent to Client** → Stored in **localStorage** or **Authorization Header**. 4️⃣ **Client Sends JWT with Requests** → Server verifies & processes request. --- ### **🔹 Why Use JWT?** ✅ **Stateless** – No need to store sessions in the database. ✅ **Secure** – Uses digital signatures to prevent tampering. ✅ **Compact** – Small size, ideal for APIs & mobile apps. ✅ **Cross-platform** – Works with any frontend & backend. --- ### **🔹 Where is JWT Used?** - **API Authentication** (Laravel API, Node.js, Django, etc.) - **Single Sign-On (SSO)** - **Secure Data Exchange** - **Authorization & Role Management** --- ### **🔹 Example: Using JWT in Laravel** #### **Install Laravel Passport (JWT Authentication)** ```sh composer require laravel/passport php artisan passport:install ``` #### **Generate JWT in Controller** ```php use Illuminate\Support\Facades\Auth; use Laravel\Passport\HasApiTokens; public function login(Request $request) { $user = Auth::attempt($request->only('email', 'password')); if (!$user) { return response()->json(['error' => 'Unauthorized'], 401); } return response()->json([ 'token' => auth()->user()->createToken('API Token')->accessToken ]); } ``` #### **Use JWT in API Request (Frontend)** ```js fetch("https://yourapi.com/profile", { headers: { Authorization: "Bearer YOUR_JWT_TOKEN" }, }); ``` ---