API Authentication sử dụng JWT trong Laravel

API Authentication sử dụng JWT trong Laravel

Hôm nay mình xin giới thiệu tới các bạn một ví dụ về API Authentication trong Laravel sử dụng JWT. Đây là một ví dụ mà mình thấy khá hữu ích trong việc xác thực người dùng trong các ứng dụng web.

1. Giới thiệu

Hôm nay mình xin giới thiệu tới các bạn một ví dụ về API Authentication trong Laravel sử dụng JWT. Đây là một ví dụ mà mình thấy khá hữu ích trong việc xác thực người dùng trong các ứng dụng web.

JSON Web Token (JWT) là một tiêu chuẩn mở (RFC 7519) định nghĩa một cách nhỏ gọn và an toàn để truyền tải thông tin giữa các bên một cách an toàn dưới dạng 1 đối tượng JSON . Các thông tin này được xác thực và có độ tin cậy cao vì nó có chứa chữ ký số (digital signature). Để hiểu rõ hơn về JWT mời bạn đọc bài viết JSON Web Token (JWT) là gì?

2. Cài đặt package JWT

Thêm package tymon/jwt-auth vào file composer.json:

composer require tymon/jwt-auth "1.0.*"

Để mã hóa token, chúng ta cần tạo secret key:

php artisan jwt:generate

Tiến hành publish file config JWT. Khi publish thành công, ta sẽ thấy file config/jwt.php được tạo mới. Để publish file config trong Laravel, chạy command line sau đây:

php artisan vendor:publish --provider="TymonJWTAuthProvidersLaravelServiceProvider"

 Mở file /app/Http/Kernel.php và thêm 2 dòng vào cuối của $routeMiddleware:

protected $routeMiddleware = [
    'auth' => AppHttpMiddlewareAuthenticate::class,
    'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
    'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
    'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
    'can' => IlluminateAuthMiddlewareAuthorize::class,
    'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
    'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
    'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
    'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,

    // THIS LINES HAS BEEN ADDED to JWT Implementation
    'jwt.auth' => TymonJWTAuthHttpMiddlewareAuthenticate::class,
    'jwt.refresh' => TymonJWTAuthHttpMiddlewareRefreshToken::class,
];

Mở file /app/User.php và impliments class JWTSubject :

getKey();
    }

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

Mặc định api authentication sử dụng token, ta sửa lại như sau:

 [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

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

Quá trình cài đặt đã xong, để kiểm tra JWT đã chạy được chưa ta tạo controller /app/Http/Controllers/APILoginController.php để thực hiện kiểm tra chức năng login:

attempt($credentials)) {
            // if the credentials are wrong we send an unauthorized error in json format
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return response()->json([
            'token' => $token,
            'type' => 'bearer', // you can ommit this
            'expires' => auth('api')->factory()->getTTL() * 60, // time to expiration
            
        ]);
    }
}

Tạo route để login và lấy token được trả về

Route::post('login', '[email protected]');

Sử dụng postman để gửi request, khi đăng nhập thành công kết quả trả về có chứa token:

admin

Leave a Reply

Your email address will not be published. Required fields are marked *