EN VI

Laravel API Sử Dụng Xác Thực JWT Auth

Để cài đặt JWT Auth thông qua composer, bạn hãy chạy lệnh sau để tải về phiên bản mới nhất:

composer require tymon/jwt-auth

Sau đó, bạn cần thêm provider vào file config/app.php (đối với Laravel 5.4 hoặc thấp hơn) như sau:

'providers' => [

    ...

    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]

Tiếp theo, bạn cần publish config bằng cách chạy lệnh sau:

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

Lúc này, bạn sẽ có file config/jwt.php để thiết lập các thông tin cơ bản cho package này.

Để tạo ra secret key, bạn có thể sử dụng lệnh helper sau:

php artisan jwt:secret

Lệnh này sẽ tự động cập nhật file .env với giá trị JWT_SECRET=foobar. Key này sẽ được sử dụng để ký các token. Cách thức ký token sẽ phụ thuộc vào thuật toán mà bạn chọn.


Chỉnh sửa Model User:

Để sử dụng JWT Auth trong ứng dụng Laravel của bạn, trước hết bạn cần implement interface Tymon\JWTAuth\Contracts\JWTSubject trên model User của bạn. Interface này yêu cầu bạn implement 2 method là getJWTIdentifier() và getJWTCustomClaims(). Ví dụ dưới đây sẽ giúp bạn hiểu được cách thực hiện này:

<?php

namespace App;

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

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    // Các thuộc tính và method khác ở đây

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

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

Sau đó, bạn cần cấu hình Auth guard để sử dụng JWT Auth. Trong file config/auth.php, hãy thực hiện các thay đổi sau:

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

...

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

Ở đây, chúng ta đang chỉ định guard "api" sử dụng driver "jwt" và provider "users". Đồng thời, chúng ta cũng đặt guard "api" làm guard mặc định.

Từ giờ, bạn có thể sử dụng hệ thống xác thực Auth của Laravel, trong đó JWT Auth sẽ thực hiện các công việc phía sau!


Thêm route:

Để thêm các route xác thực cơ bản, bạn cần thêm các route sau vào file routes/api.php:

Route::group([
    'middleware' => 'api',
    'prefix' => 'auth'
], function ($router) {
    Route::post('login', 'AuthController@login');
    Route::post('logout', 'AuthController@logout');
    Route::post('refresh', 'AuthController@refresh');
    Route::post('me', 'AuthController@me');
});

Sau đó, bạn cần tạo ra AuthController, có thể tạo thủ công hoặc chạy lệnh artisan:

php artisan make:controller AuthController

Tiếp theo, bạn cần thêm code sau vào AuthController:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

    public function login()
    {
        $credentials = request(['email', 'password']);

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

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

    public function me()
    {
        return response()->json(auth()->user());
    }

    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

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

Bây giờ, bạn có thể gửi POST request đến endpoint login (ví dụ: http://example.dev/auth/login) với các thông tin xác thực hợp lệ và nhận được kết quả như sau:

{
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ",
    "token_type": "bearer",
    "expires_in": 3600
}

Token này có thể được sử dụng để thực hiện các request đã được xác thực trong ứng dụng của bạn.


Có nhiều cách để gửi token qua http như:

- Header Authorization

    Authorization: Bearer eyJhbGciOiJIUzI1NiI...

- Query string parameter

    http://example.dev/me?token=eyJhbGciOiJIUzI1NiI...

Rating: 10 (1 Votes)
Comment

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login