📜  jwt laravel - SQL (1)

📅  最后修改于: 2023-12-03 15:02:28.426000             🧑  作者: Mango

JWT Laravel - SQL

Introduction

In modern software development, security is a top priority. One of the ways to secure web applications is by implementing authentication and authorization using JSON Web Tokens (JWTs). Laravel provides a simple and easy-to-use package called tymon/jwt-auth for JWT authentication.

However, using JWTs also requires connecting to a database to retrieve the user details and generate the tokens. In this tutorial, we will explore how to use JWT authentication in Laravel with SQL as the backend database.

Prerequisites

Before we begin, ensure that you have the following installed on your system:

  • PHP and Composer
  • Laravel
  • MySQL or MariaDB
  • Postman or any other API client
Installation

First, create a new Laravel project using the following command:

composer create-project laravel/laravel jwt-laravel-sql

Next, install the JWT package:

composer require tymon/jwt-auth

After installation, run the JWT setup command:

php artisan jwt:secret

This command will generate a random 32-character secret key in your .env file.

Next, configure the database connection in the .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=jwt_laravel_sql
DB_USERNAME=root
DB_PASSWORD=

Create a new database jwt_laravel_sql in your MySQL/MariaDB server.

Creating the User Model and Table

Create a new model for the users using the following command:

php artisan make:model User -m

This command will generate a new model file in app/Models and a migration file in database/migrations.

Open the migration file and modify it as follows:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->timestamps();
    });
}

In the User model, add the jwt-auth trait and the necessary implementations:

use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use HasFactory, Notifiable, \Tymon\JWTAuth\Contracts\JWTSubject;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }
}
Creating the Authentication Routes and Controllers

Create a new controller for the authentication using the following command:

php artisan make:controller AuthController

In the AuthController, add the methods for registration and login:

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

        if($validator->fails()){
            return response()->json($validator->errors(), 400);
        }

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ]);

        $token = Auth::login($user);

        return $this->respondWithToken($token);
    }

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

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

        return $this->respondWithToken($token);
    }

    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }
}
Creating the Authentication Middleware

Create a new middleware for the authentication using the following command:

php artisan make:middleware JwtMiddleware

In the JwtMiddleware, add the implementation using jwt-auth package:

use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Exception;

class JwtMiddleware
{
    public function handle($request, Closure $next)
    {
        try {
            $user = JWTAuth::parseToken()->authenticate();
        } catch (Exception $e) {
            if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
                return response()->json(['error' => 'Token is invalid'], 401);
            }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
                return response()->json(['error' => 'Token is expired'], 401);
            }else{
                return response()->json(['error' => 'Token not found'], 401);
            }
        }
        return $next($request);
    }
}
Registering the Authentication Routes and Middleware

Register the authentication routes in routes/api.php:

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

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

Register the middleware in app/Http/Kernel.php:

protected $routeMiddleware = [
    // ...
    'jwt.verify' => \App\Http\Middleware\JwtMiddleware::class,
];
Testing the Authentication

Run the Laravel development server:

php artisan serve

Use Postman to test the authentication by sending a POST request to the register endpoint with the following data:

{
    "name": "John Doe",
    "email": "john.doe@example.com",
    "password": "password",
    "password_confirmation": "password"
}

The response should contain a JWT token.

Use the token to send a GET request to the user endpoint. The response should contain the user details.

Conclusion

In this tutorial, we have explored how to use JWT authentication with Laravel and SQL as the backend database. By following these steps, you can secure your Laravel applications using JWTs and SQL.