Latest Post

Tăng thứ hạng và truy cập tự nhiên với 10 phương pháp SEO hay nhất Kiếm Tiền Online (mmo): Khái Niệm và Các Hình Thức Phổ Biến

Khi sử dụng Laravel Passport để thực hiện xác thực, chúng ta sẽ tập trung vào việc xác thực thông qua các API. Điều quan trọng là chúng ta cần phải xây dựng những API cần thiết để thực hiện quá trình xác thực. Hệ thống API xác thực này bao gồm các Route sau đây:

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

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 AppHttpControllers;

use AppModelsUser;
use CarbonCarbon;
use IlluminateHttpJsonResponse;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
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.

Hi vọng rằng bạn đã hiểu cách thực hiện quá trình xác thực bằng Laravel Passport. Bài viết sẽ kết thúc ở đây. Nếu bạn có bất kỳ câu hỏi hoặc điểm cần thảo luận thêm, đừng ngần ngại để lại bình luận phía dưới. Chúng ta sẽ cùng giải quyết nó.

Trả lời

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 *