How to Implement User Authentication in Laravel with JWT

Learn how to set up user authentication in Laravel using JWT for secure API access.

Laravel JWT Authentication Web Development UK Business

Secure user authentication in Laravel with JWT

Understanding JWT and Its Benefits

JSON Web Tokens (JWT) are a popular way to handle user authentication in web applications. Unlike traditional session-based authentication, JWTs are stateless, meaning they don’t require storing user sessions on the server. This is particularly beneficial for applications that scale across multiple servers or require a mobile interface.

For UK small businesses looking to enhance the security of their applications, implementing JWT can significantly streamline the authentication process. It provides a reliable way to verify users without compromising performance.

Setting Up Your Laravel Project

Before we dive into JWT, let’s ensure you have a Laravel project set up. If you haven’t done this yet, you can create a new Laravel application using Composer:

composer create-project --prefer-dist laravel/laravel jwt-auth-app

Installing Required Packages

To manage JWT in your Laravel application, we’ll use the tymon/jwt-auth package. Install it via Composer:

composer require tymon/jwt-auth

Once installed, publish the configuration file with the following command:

php artisan vendor:publish --provider="Tymon\JWTAuth\JWTAuthServiceProvider"

Next, you need to generate a secret key for JWT:

php artisan jwt:secret

Configuring User Model

Open your User model (usually located at app/Models/User.php) and implement the JWTSubject interface:

use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject {
    public function getJWTIdentifier() {
        return $this->getKey();
    }

    public function getJWTCustomClaims() {
        return [];
    }
}

Creating Authentication Logic

Next, we need to create a controller that will handle the authentication process. You can create a new controller using Artisan:

php artisan make:controller AuthController

Implementing Login Method

In your AuthController, implement the login method to generate a JWT token:

use Tymon\JWTAuth\JWTAuth;
use Illuminate\Http\Request;

public function login(Request $request) {
    $credentials = $request->only('email', 'password');

    if (!$token = JWTAuth::attempt($credentials)) {
        return response()->json(['error' => 'invalid_credentials'], 401);
    }

    return response()->json(compact('token'));  
}

Implementing Logout Method

To log a user out, you can create a logout method in the same controller:

public function logout() {
    JWTAuth::invalidate(JWTAuth::getToken());
    return response()->json(['message' => 'Successfully logged out']);
}

Routes for Authentication

Now that we have our controller set up, we need to define routes for login and logout. Open the routes/api.php file and add the following:

use App\Http\Controllers\AuthController;

Route::post('login', [AuthController::class, 'login']);
Route::post('logout', [AuthController::class, 'logout']);

Protecting Routes with Middleware

To protect certain routes in your application, you can use middleware to ensure that only authenticated users can access them. Laravel provides a built-in middleware for JWT authentication.

First, ensure you add the jwt.auth middleware to your routes. For example:

Route::group(['middleware' => 'jwt.auth'], function() {
    Route::get('user', function(Request $request) {
        return response()->json($request->user());
    });
});

Testing Your Authentication

To test your authentication setup, use tools like Postman or Insomnia. When you send a POST request to the /api/login endpoint with valid credentials, you should receive a JWT token in the response. You can then use this token in the header of subsequent requests to access protected routes.

Conclusion

Implementing user authentication in Laravel using JWT is a straightforward process that enhances the security of your application without compromising performance. With the steps outlined above, you should be well on your way to setting up a robust authentication system for your business.

If you need assistance with implementing JWT or any other Laravel features, feel free to get in touch. I'm here to help you optimise your web applications for success.

Comments

No comments yet. Be the first to comment.

Next 3 Blogs

Need something built?

Laravel, AI integrations, API connections, or a full custom site - fixed-price projects for UK businesses.

Request a quote