<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arif Hassan on Medium]]></title>
        <description><![CDATA[Stories by Arif Hassan on Medium]]></description>
        <link>https://medium.com/@aarifhsn?source=rss-0f44537a5cb2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pJWefQ0SEplTrpJyQSzlrQ.jpeg</url>
            <title>Stories by Arif Hassan on Medium</title>
            <link>https://medium.com/@aarifhsn?source=rss-0f44537a5cb2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:42:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aarifhsn/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[JWT Authentication in Laravel & PHP]]></title>
            <link>https://medium.com/@aarifhsn/jwt-authentication-in-laravel-php-72b47818b072?source=rss-0f44537a5cb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/72b47818b072</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Arif Hassan]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 18:56:42 GMT</pubDate>
            <atom:updated>2025-02-27T18:56:42.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*YbBqvrv0OzDM6e-oB2PgXg.png" /></figure><p>If you’re building a website or app that requires user authentication, you need a secure way to verify users and control what they can access. This is where JWT (JSON Web Token) comes in.</p><h3>What is JWT?</h3><p>JWT stands for JSON Web Token. It is a secure, compact, and URL-safe way to transmit data between a client (browser/app) and a server.</p><p>🔹 Think of JWT like a digital passport ️. When you travel, immigration stamps your passport to confirm your identity. Similarly, when you log in, the server gives you a JWT, which proves who you are.</p><p>🔹 This token contains encoded information about the user, like their ID, role (admin/user), and permissions.</p><p>🔹 The best part? JWT is stateless — the server doesn’t need to store any session data! Instead, the client (browser or mobile app) keeps the token and sends it with every request.</p><h3>Why Do We Need JWT?</h3><p>* <strong>Traditional Authentication (Session-Based Login)</strong></p><ul><li>When a user logs in, the server stores their session in a database.</li><li>Every time the user makes a request, the server checks the session.</li><li>This works but becomes slow and hard to scale (e.g., in microservices or APIs).</li></ul><p>* <strong>JWT Authentication (Token-Based Login)</strong></p><ul><li>The server gives the user a JWT after login.</li><li>The client stores this token and sends it with every request.</li><li>The server verifies the token and grants or denies access.</li><li>No session storage is needed, so it’s faster and more scalable!</li></ul><p># <strong>JWT is commonly used in:</strong><br>*️ REST APIs &amp; Microservices<br>*️ Mobile &amp; Web Apps<br>*️ Single Sign-On (SSO)</p><h3># How JWT Works (Step-by-Step)</h3><p><strong>1. User Logs In</strong></p><ul><li>The user enters their email &amp; password.</li><li>The server checks the credentials.</li></ul><p><strong>2. Server Creates a JWT</strong></p><ul><li>If the login is successful, the server generates a JWT.</li><li>The token is signed with a secret key so it cannot be tampered with.</li><li>The JWT contains information like:</li></ul><pre>{<br>  &quot;user_id&quot;: 123,<br>  &quot;role&quot;: &quot;admin&quot;,<br>  &quot;exp&quot;: 1700000000  // Expiration time<br>}</pre><p><strong>3. Client Stores the Token</strong></p><ul><li>The JWT is sent to the client (browser or app).</li><li>It can be stored in localStorage, sessionStorage, or HTTP-only cookies.</li></ul><p><strong>4.</strong> <strong>Client Requests a Protected Resource</strong></p><ul><li>When the client wants to access secure data, it sends the JWT in the Authorization header:</li></ul><pre>GET /profile  <br>Authorization: Bearer &lt;your_jwt_here&gt;</pre><p><strong>5.</strong> <strong>Server Verifies the JWT</strong></p><ul><li>The server decodes the JWT and checks:<br>- Is the signature valid?<br>- Is the token expired?<br>- Does the user have permission?</li></ul><p><strong>6. Access Granted or Denied</strong></p><ul><li>If the token is valid, the server returns the requested data.</li><li>The user must log in again if the token is invalid or expired.</li></ul><h3>JWT Structure (3 Parts)</h3><p>A JWT has three parts, separated by dots (.):</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsInJvbGUiOiJhZG1pbiJ9.s0m3s3cr3tk3y</pre><p><strong>1. Header</strong> (contains metadata)</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,  // Algorithm used to sign the token<br>  &quot;typ&quot;: &quot;JWT&quot;     // Token type<br>}</pre><p><strong>2.</strong> <strong>Payload</strong> (contains user data)</p><pre>{<br>  &quot;user_id&quot;: 123,<br>  &quot;role&quot;: &quot;admin&quot;,<br>  &quot;exp&quot;: 1700000000<br>}</pre><p><strong>3. Signature</strong> (used to verify the token’s integrity)</p><pre>HMACSHA256(<br>  base64UrlEncode(header) + &quot;.&quot; + base64UrlEncode(payload),<br>  secret_key<br>)</pre><h3>Implementing JWT in Laravel</h3><p>Laravel has built-in authentication, but if you want to use JWT for <strong>API authentication</strong>, you can use the tymon/jwt-auth package.</p><h3>Step 1: Install JWT Package in Laravel</h3><p>First, install the JWT authentication package using Composer:</p><pre>composer require tymon/jwt-auth</pre><p>Then, publish the package configuration:</p><pre>php artisan vendor:publish --provider=&quot;Tymon\JWTAuth\Providers\LaravelServiceProvider&quot;</pre><p>This will create a config/jwt.php file.</p><p>Now, generate a secret key:</p><pre>php artisan jwt:secret</pre><p>This will update your .env file with a JWT_SECRET key.</p><h3>Step 2: Configure Auth in Laravel</h3><p>Modify config/auth.php to use JWT as the default authentication guard for APIs.</p><p>Find this section:</p><pre>&#39;guards&#39; =&gt; [<br>    &#39;api&#39; =&gt; [<br>        &#39;driver&#39; =&gt; &#39;token&#39;,<br>        &#39;provider&#39; =&gt; &#39;users&#39;,<br>    ],<br>],</pre><p>Change &#39;token&#39; to &#39;jwt&#39; like this:</p><pre>&#39;guards&#39; =&gt; [<br>    &#39;api&#39; =&gt; [<br>        &#39;driver&#39; =&gt; &#39;jwt&#39;,<br>        &#39;provider&#39; =&gt; &#39;users&#39;,<br>    ],<br>],</pre><h3>Step 3: Create an Authentication Controller</h3><p>Run this command to generate an AuthController:</p><pre>php artisan make:controller AuthController</pre><p>Now, add the following methods to AuthController.php:</p><p>Register User and Generate JWT</p><pre>use App\Models\User;<br>use Illuminate\Http\Request;<br>use Illuminate\Support\Facades\Hash;<br>use Tymon\JWTAuth\Facades\JWTAuth;</pre><pre>class AuthController extends Controller<br>{<br>    public function register(Request $request)<br>    {<br>        $request-&gt;validate([<br>            &#39;name&#39; =&gt; &#39;required|string|max:255&#39;,<br>            &#39;email&#39; =&gt; &#39;required|string|email|max:255|unique:users&#39;,<br>            &#39;password&#39; =&gt; &#39;required|string|min:6&#39;<br>        ]);</pre><pre>        $user = User::create([<br>            &#39;name&#39; =&gt; $request-&gt;name,<br>            &#39;email&#39; =&gt; $request-&gt;email,<br>            &#39;password&#39; =&gt; Hash::make($request-&gt;password),<br>        ]);</pre><pre>        $token = JWTAuth::fromUser($user);</pre><pre>        return response()-&gt;json([<br>            &#39;user&#39; =&gt; $user,<br>            &#39;token&#39; =&gt; $token<br>        ]);<br>    }</pre><p>Login User and Generate Token</p><pre>public function login(Request $request)<br>{<br>    $credentials = $request-&gt;only(&#39;email&#39;, &#39;password&#39;);</pre><pre>    if (!$token = JWTAuth::attempt($credentials)) {<br>        return response()-&gt;json([&#39;error&#39; =&gt; &#39;Invalid credentials&#39;], 401);<br>    }</pre><pre>    return response()-&gt;json([<br>        &#39;token&#39; =&gt; $token<br>    ]);<br>}</pre><p>Get Authenticated User</p><pre>public function userProfile()<br>{<br>    return response()-&gt;json(auth()-&gt;user());<br>}</pre><p>Logout User</p><pre>public function logout()<br>{<br>    auth()-&gt;logout();<br>    return response()-&gt;json([&#39;message&#39; =&gt; &#39;Successfully logged out&#39;]);<br>}</pre><h3>Step 4: Define Routes for Authentication</h3><p>Open routes/api.php and add the following routes:</p><pre>use App\Http\Controllers\AuthController;</pre><pre>Route::post(&#39;/register&#39;, [AuthController::class, &#39;register&#39;]);<br>Route::post(&#39;/login&#39;, [AuthController::class, &#39;login&#39;]);</pre><pre>Route::middleware(&#39;auth:api&#39;)-&gt;group(function () {<br>    Route::get(&#39;/profile&#39;, [AuthController::class, &#39;userProfile&#39;]);<br>    Route::post(&#39;/logout&#39;, [AuthController::class, &#39;logout&#39;]);<br>});</pre><h3>Step 5: Protect Routes with Middleware</h3><p>Open app/Http/Kernel.php and register the JWT authentication middleware:</p><pre>protected $routeMiddleware = [<br>    &#39;jwt.auth&#39; =&gt; \Tymon\JWTAuth\Http\Middleware\Authenticate::class,<br>];</pre><p>Now, protect your API routes by adding middleware(&#39;jwt.auth&#39;):</p><pre>Route::middleware([&#39;jwt.auth&#39;])-&gt;group(function () {<br>    Route::get(&#39;/profile&#39;, [AuthController::class, &#39;userProfile&#39;]);<br>});</pre><h3>Step 6: Test JWT Authentication</h3><p>You can test JWT authentication using Postman or CURL.</p><h4>Register User</h4><pre>POST http://yourdomain.com/api/register<br>Content-Type: application/json</pre><pre>{<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;email&quot;: &quot;john@example.com&quot;,<br>    &quot;password&quot;: &quot;password123&quot;<br>}</pre><p>Response:</p><pre>{<br>    &quot;user&quot;: {<br>        &quot;id&quot;: 1,<br>        &quot;name&quot;: &quot;John Doe&quot;,<br>        &quot;email&quot;: &quot;john@example.com&quot;<br>    },<br>    &quot;token&quot;: &quot;your_jwt_token_here&quot;<br>}</pre><h3><strong>Login User</strong></h3><pre>POST http://yourdomain.com/api/login<br>Content-Type: application/json</pre><pre>{<br>    &quot;email&quot;: &quot;john@example.com&quot;,<br>    &quot;password&quot;: &quot;password123&quot;<br>}</pre><p>Response:</p><pre>{<br>    &quot;token&quot;: &quot;your_jwt_token_here&quot;<br>}</pre><p>Access Protected Route (Profile)</p><pre>GET http://yourdomain.com/api/profile<br>Authorization: Bearer your_jwt_token_here</pre><p>Response:</p><pre>{<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;John Doe&quot;,<br>    &quot;email&quot;: &quot;john@example.com&quot;<br>}</pre><h3>Implementing JWT in Pure PHP (Without Laravel)</h3><p>If you’re using <strong>plain PHP</strong>, you can still implement JWT authentication using the firebase/php-jwt package.</p><h3>Step 1: Install JWT Package</h3><pre>composer require firebase/php-jwt</pre><p><strong>Step 2: Generate JWT Token</strong></p><pre>use Firebase\JWT\JWT;</pre><pre>$secret_key = &quot;your_secret_key&quot;;<br>$payload = [<br>    &quot;user_id&quot; =&gt; 123,<br>    &quot;exp&quot; =&gt; time() + (60 * 60) // Token expires in 1 hour<br>];</pre><pre>$token = JWT::encode($payload, $secret_key, &#39;HS256&#39;);</pre><pre>echo json_encode([&quot;token&quot; =&gt; $token]);</pre><p><strong>Step 3: Decode and Verify JWT Token</strong></p><pre>use Firebase\JWT\JWT;<br>use Firebase\JWT\Key;</pre><pre>$token = $_GET[&#39;token&#39;]; // Get token from request</pre><pre>try {<br>    $decoded = JWT::decode($token, new Key($secret_key, &#39;HS256&#39;));<br>    echo json_encode($decoded);<br>} catch (Exception $e) {<br>    echo json_encode([&quot;error&quot; =&gt; &quot;Invalid token&quot;]);<br>}</pre><h3>Best Practices for JWT Authentication</h3><p>- Use HTTP-only cookies instead of local storage for security.<br>- Set expiration times (exp) to prevent token misuse.<br>- Store JWT secret keys securely (in .env file).<br>- Use refresh tokens for long-lived sessions.<br>- Limit token scope—store only necessary user data in the payload.</p><p>JWT is an efficient, scalable, and secure way to handle authentication and authorization in modern applications. It eliminates the need for server-side session storage and works perfectly in microservices, APIs, and mobile apps.</p><p>If you’re building a secure login system, an API, or a scalable web app, JWT is the way to go!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72b47818b072" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>