Mountains

API Authentication sử dụng JWT trong Laravel PHP

Tên bài học: API Authentication sử dụng JWT trong Laravel PHP

Thời gian học: 1 giờ | Nguồn: VnCoder | Lượt xem: 730 lượt xem

Nội dung bài học:

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="Tymon\JWTAuth\Providers\LaravelServiceProvider"

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

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,

    // THIS LINES HAS BEEN ADDED to JWT Implementation
    'jwt.auth' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class,
    'jwt.refresh' => \Tymon\JWTAuth\Http\Middleware\RefreshToken::class,
];

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

<?php


namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

// Please add this line
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{

    // BODY OF THIS CLASS    

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

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

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

<?php

// OTHER ARRAYS

 'guards' => [
    '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:

<?php


namespace app\Http\Controllers;

use Illuminate\Http\Request;

class APILoginController extends Controller
{
    
    public function login() 
    {
        // get email and password from request
        $credentials = request(['email', 'password']);
        
        // try to auth and get the token using api authentication
        if (!$token = auth('api')->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', 'APILoginController@login');

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


Bạn có muốn xác nhận hoàn thành bài học này không?


Xác nhận hoàn thành bài học


Copyright Disclaimer

This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.


Tuyên bố từ chối trách nhiệm bản quyền

Trang web này không lưu trữ bất kỳ tệp (files) nào trên máy chủ (server). Chúng tôi chỉ lập chỉ mục và liên kết đến nội dung được cung cấp bởi các trang web khác. Vui lòng liên hệ với các nhà cung cấp nội dung để xóa nội dung bản quyền nếu có và gửi email cho chúng tôi, chúng tôi sẽ xóa các liên kết hoặc nội dung có liên quan ngay lập tức.

Bình luận bài viết

Đăng bình luận

0 bình luận