Danh sách Tutorial

Xác thực Authentication với Laravel Passport


Xác thực với Laravel Passport, chúng ta sẽ xác thực qua API vì vậy chúng ta cần xây dựng các API để xác thực. Hệ thống API xác thực gồm các Route sau:

Method EndPoint Middleware Giải thích
POST /api/auth/login Đăng nhập
POST /api/auth/register Đăng ký
DELETE /api/auth/logout api:auth Đăng xuất
GET /api/auth/user api:auth Lấy thông tin đăng nhập của user

Xây dựng hệ thống xác thực qua Laravel Passport

Trước khi bước vào code hệ thống xác thực các bạn cần tham khảo cài đặt Laravel Passport ở đây:

Sau khi cài đặt xong thì hãy thực hiện các bước dưới đây:

Bước 1: Đầu tiên chúng ta define các route ở file: routes/api.php thêm đoạn code sau:

// Authentication API with Passport
Route::group([
    'prefix' => 'auth'
], function () {
    Route::post('login', [AuthController::class, 'login']);
    Route::post('register', [AuthController::class, 'register']);
    Route::group([
        'middleware' => 'auth:api'
    ], function() {
        Route::delete('logout', [AuthController::class, 'logout']);
        Route::get('user', [AuthController::class, 'user']);
    });
});

Chúng ta kiểm tra lại bằng lệnh: php artisan route:list

Bước 2: Tạo AuthController để handle xử lý xác thực

Chạy command sau để tạo Controller

php artisan make:controller AuthController

Nó sẽ tạo ra file app/Http/Controllers/AuthController.php, chúng ta sửa nội dung của file như sau:

<?php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function register(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string',
            'email' => 'required|string|email|unique:users',
            'password' => 'required|string|confirmed'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'fails',
                'message' => $validator->errors()->first(),
                'errors' => $validator->errors()->toArray(),
            ]);
        }

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

        $user->save();

        return response()->json([
            'status' => 'success',
        ]);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function login(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|string|email',
            'password' => 'required|string',
            'remember_me' => 'boolean'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'fails',
                'message' => $validator->errors()->first(),
                'errors' => $validator->errors()->toArray(),
            ]);
        }

        $credentials = request(['email', 'password']);

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

        $user = $request->user();
        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;

        if ($request->input('remember_me')) {
            $token->expires_at = Carbon::now()->addWeeks(1);
        }

        $token->save();

        return response()->json([
            'status' => 'success',
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
        ]);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function logout(Request $request): JsonResponse
    {
        $request->user()->token()->revoke();
        return response()->json([
            'status' => 'success',
        ]);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function user(Request $request): JsonResponse
    {
        return response()->json($request->user());
    }
}

Thử ngiệm hệ thống xác thực

Bạn có thể setup 1 web server hoặc có thể chạy web server bằng command sau:

php artisan serve --port=8001

Bây giờ chúng ta sử dụng công cụ Postman để test api nhé

Test Register API (Đăng ký)

Chúng ta sẽ gửi các thông tin sau với method là POST

  • name: Họ và tên
  • email: Địa chỉ email sử dụng để đăng nhập
  • password: Mật khẩu sử dụng để đăng nhập
  • password_confirmation: Xác nhận mật khẩu

Test Login API (Đăng nhập)

Chúng ta đã đăng ký thành công bản ghi vào! Giờ hãy thử login xem

Chúng ta sử dụng emailpassword để đăng nhập tới API Login của Passport

Chú ý: 2 field trả về là “access_token” và “token_type” bạn cần lưu nó lại để sử dụng cho những api có middleware api:auth

Lấy thông tin user đã đăng nhập

Set phương thức: Authorization Type là: Bearer

Token: Nhập token lấy được sau khi login.

Tạo 1 request GET tới end point của Laravel có tham số header X-Requested-With = XMLHttpRequest

Đây là cách sử dụng Postman, còn khi bạn code thì hãy set 2 header parameter là:

  • Authorization: <token_type> <access_token>
  • X-Requested-With: XMLHttpRequest

Chúng ta sẽ lấy được thông tin user đang login.

Test Logout API (Đăng xuất)

Chúng ta đã logout thành công.

Hy vọng các bạn đã nắm được quy trình xác thực của Laravel Passport. Bài viết này xin dừng ở đây, có gì thắc mắc, các bạn vui lòng comment bên dưới.

Nguồn: vinasupport.com

SHARE

Có 3 bình luận trong bài viết “Xác thực Authentication với Laravel Passport”

  1. hayyy

    bài viết chi tiết hay we

  2. thanh

    add ơi, sao chỗ function user mình lấy thông tin token và login bị null. check trên postman ra lỗi:TypeError: Laravel\Passport\PassportUserProvider::__construct(): Argument #1 ($provider) must be of type Illuminate\Contracts\Auth\UserProvider, null given in PassportServiceProvider.php.
    Support mình với!

mode_edit Bình luận của bạn

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

account_circle
web