Xác thực Authentication với Laravel Passport
Xác thực bằng Laravel Passport, chúng ta sẽ xác thực qua API nên chúng ta cần xây dựng các API để xác thực. Hệ thống API xác thực bao gồm các tuyến sau:
Cách | EndPoint | Phần mềm trung gian | Giải thích |
ĐĂNG TẢI | / api / auth / login | Đăng nhập | |
ĐĂNG TẢI | / api / auth / register | Sự đăng ký | |
XÓA BỎ | / api / auth / logout | api: auth | Đăng xuất |
MẮC PHẢI | / api / auth / user | api: auth | Nhận thông tin đăng nhập của người dùng |
Xây dựng hệ thống xác thực qua Laravel Passport
Trước khi nhập mã hệ thống xác thực, bạn cần tham khảo cách cài đặt Laravel Passport tại đây:
Sau khi cài đặt xong, hãy làm theo các bước sau:
Bước 1: Đầu tiên, chúng tôi xác định các tuyến đường trong File: route / api.php thêm mã 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: tuyến đường nghệ nhân php: danh sách

Bước 2: Tạo AuthController để xử lý xác thực
Chạy lệnh sau để tạo Bộ điều khiển
php artisan make:controller AuthController
Nó sẽ tạo ra File app / Http / Controllers / AuthController.phpchúng tôi chỉnh 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()); } }
Kiểm tra hệ thống xác thực
Bạn có thể thiết lập một máy chủ web hoặc bạn có thể chạy một máy chủ web bằng lệnh sau:
php artisan serve --port=8001
Bây giờ chúng tôi sử dụng công cụ Postman để kiểm tra api
API đăng ký thử nghiệm (Đăng ký)
Chúng tôi sẽ gửi thông tin sau với phương thức POST
- Tên: Họ và tên
- e-mail: Địa chỉ email được sử dụng để đăng nhập
- mật khẩu mở Key: Mật khẩu dùng để đăng nhập
- xác nhận mật khẩu: Xác nhận mật khẩu
Kiểm tra API đăng nhập (Đăng nhập)
Chúng tôi đã đăng ký thành công đăng nhập! Bây giờ hãy thử đăng nhập
Chúng tôi sử dụng e-mail và mật khẩu mở Key để đăng nhập vào API đăng nhập của Passport
Lưu ý: 2 trường trả về là “access_token” và “token_type” bạn cần lưu lại để sử dụng cho api với middleware api: auth
Nhận thông tin người dùng đã đăng nhập
Phương thức đặt: Loại ủy quyền là: Người mang
Token: Nhập mã thông báo nhận được sau khi đăng nhập.
Thực hiện một yêu cầu GET tới điểm cuối của Laravel với X-Request-With =. tham số tiêu đề XMLHttpRequest
Đây là cách sử dụng Postman và khi bạn viết mã, hãy đặt 2 tham số tiêu đề:
- Ủy quyền:
- X-Request-With: XMLHttpRequest
Chúng tôi sẽ lấy thông tin người dùng đăng nhập.
Kiểm tra API đăng xuất (Đăng xuất)
Chúng tôi đã đăng xuất thành công.
Hy vọng bạn đã hiểu rõ về quy trình xác thực của Laravel Passport. Bài viết này xin dừng tại đây, nếu có thắc mắc các bạn comment bên dưới.
Nguồn: vinasupport.com