Home >PHP Framework >Laravel >Laravel development: How to implement API authentication using Laravel Passport?
Laravel is an open source PHP web application framework designed to help developers easily build efficient web applications. Laravel Passport is part of the Laravel framework. It is an authentication server that implements the OAuth2 protocol and provides powerful support for API development. In this article, we will cover how to implement API authentication using Laravel Passport.
Before using Laravel Passport, we need to install it first. Laravel Passport can be installed by running the following command:
composer require laravel/passport
After the installation is complete, you also need to run the php artisan migrate
command to create the required data tables.
To use Laravel Passport for API authentication, we need to use it in conjunction with Laravel's authentication middleware. You can add the corresponding authentication middleware for the API group in the app/Http/Kernel.php
file:
protected $middlewareGroups = [ 'api' => [ 'throttle:60,1', IlluminateRoutingMiddlewareSubstituteBindings::class, LaravelPassportHttpMiddlewareCreateFreshApiToken::class, ], ];
Among them, the CreateFreshApiToken
middleware will be used in each request Check the API token in and automatically refresh it if needed.
Next, we need to create the corresponding authentication route for the API. The following routes can be added in the routes/api.php
file:
Route::post('login', 'APIAuthController@login'); Route::post('register', 'APIAuthController@register'); Route::group(['middleware' => ['auth:api']], function() { Route::get('details', 'APIAuthController@details'); // 添加更多需要登录才能访问的API路由 });
In the above code, the auth:api
middleware will ensure that only those who have been authenticated Only users can access these routes. AuthController
is the controller we will create later that contains the logic to handle authentication and API routing.
Now, we need to create the controller that handles API authentication and routing. AuthController
can be created using the following command:
php artisan make:controller API/AuthController
AuthController
should contain the following method:
use IlluminateHttpRequest; use IlluminateSupportFacadesAuth; use IlluminateSupportFacadesValidator; use AppUser; class AuthController extends Controller { /** * 用户注册 * * @param IlluminateHttpRequest $request * @return IlluminateHttpResponse */ public function register(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|string|max:255', 'email' => 'required|string|email|unique:users', 'password' => 'required|string|min:6', ]); if ($validator->fails()){ return response(['errors'=>$validator->errors()->all()], 400); } $request['password'] = bcrypt($request['password']); $user = User::create($request->toArray()); $token = $user->createToken('MyApp')->accessToken; return response(['token' => $token], 200); } /** * 用户登录 * * @param IlluminateHttpRequest $request * @return IlluminateHttpResponse */ public function login(Request $request) { $validator = Validator::make($request->all(), [ 'email' => 'required|string|email', 'password' => 'required|string', ]); if ($validator->fails()) { return response(['errors'=>$validator->errors()->all()], 400); } if (!Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) { return response(['message' => 'Invalid login credentials'], 400); } $user = $request->user(); $token = $user->createToken('MyApp')->accessToken; return response(['token' => $token], 200); } /** * 获取用户详细信息 * * @param IlluminateHttpRequest $request * @return IlluminateHttpResponse */ public function details(Request $request) { return response()->json(['user' => $request->user()], 200); } }
register()
method Used for user registration, the login()
method is used for user login, and the details()
method is used to obtain the detailed information of the logged in user. It should be noted that the register()
and login()
methods will create a new API token for the authenticated user and return it to the client.
Now we can test API authentication by sending username and password. The following command can be executed using a tool like Postman or curl:
curl -X POST http://your-app-url/api/login -H 'content-type: application/json' -d '{ "email": "user@example.com", "password": "password" }'
If the username and password are correct, a response containing the API token will be received:
{ "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImU4YmI2Njk0MGEyNmIzY2Q2ZmY4M2Q3MjQ5ZjgzODE1MTI2ZmRkMDIyM2YyMzVmOGZmNjhlOWM5NGU2Mzk4ZTU3ZWZiMDJhNmQyZmRlZjA2In0.eyJhdWQiOiIxIiwianRpIjoiZThiYjY2OTAwZTI2YjNjZDZmZjgzZDcyNDlmODM4MTUxMjZmZGQwMjIzZjIzNWY4ZmY2OGU5Yzk0ZTYzOThlNTdlZmIwMmE2ZDJmZGVmMDYiLCJpYXQiOjE2Mjg5NDM3NzQsIm5iZiI6MTYyODk0Mzc3NCwiZXhwIjoxNjMxMDQ5Nzc0LCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.toR762TgsNDarQZs6azl-jg-tP2996vzUc-LOQB90Twcb0Y3BC5vrd3jDW70QQw961MwV_sFrU1dhyKLMN76lG6B03zv6GjU6tLHyrqQi88t0clSrVupAcaQHOAB0gGLBRAOc5Ql1z9CHXx8f_FkA3RVC4htHNTk_r0mM-szWcf1sRONQYaARPDFl7ZJwj1_wYB7M6dcpiEDDhpyzmRFPv7pYyX8805BL4yg6z-Kmxc-DW4GSS4NTBxnctwGPf9w8fYc2zJGHXmT6OtqVjuqKDdFQgxIQhEkeSldBZmzTIPIR_tTa8Ub3Cxlx69zAfJTHosXwPYQOO03LBJwNVdjeLIkKgQK1PcAXD2kN4-RuyTEMXYNQ0wRGaHIb3vxwqVdjrrVE9yrDMIpAPRgzFwzXbJWvKmxzZpFTUz9RvIqUFt2zNbIG5kLOUyvmKIqO-aTISCT0wu0T0ZEq-DpXJ7-C6z-M0cJJP37y7eV4jdAMx7yD9jT85Knv4_hjLyKvF4We5DSSOYjeIVoq3XHNJdmYJ7X3ph6Ko1CfdtVKNVf20Vx8Z_Zi-pe9bTY0n-tSkwDvVXpVOrb3BOalq7MbOpTe8Klf9uZ_ZIDqTlTnrYV_oh_5isrImv7r8D1NX1G4p9jRcI16MEFDE" }
Then, another command can be used To access routes that require authentication:
curl -X GET http://your-app-url/api/details -H 'authorization: Bearer <token>'
In the above command, replace d6fb5a6237ab04b68d3c67881a9080fa
with the API token obtained in the previous step. If the token is valid, you will get an authenticated response:
{ "user": { "id": 1, "name": "User", "email": "user@example.com", "email_verified_at": null, "created_at": "2021-08-13T02:58:04.000000Z", "updated_at": "2021-08-13T02:58:04.000000Z" } }
In this article, we covered how to implement API authentication using Laravel Passport. Using Laravel Passport, you can easily add strong authentication support to your web API, making your user data more secure. Laravel Passport also provides other powerful features such as API access token management and OAuth2 client management. If you are a Laravel developer, be sure to learn more about Laravel Passport and use it in your next web project.
The above is the detailed content of Laravel development: How to implement API authentication using Laravel Passport?. For more information, please follow other related articles on the PHP Chinese website!