


Laravel development: How to implement API authentication using Laravel Passport?
Jun 13, 2023 pm 05:34 PMLaravel 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.
- Install 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.
- Configure Authentication Middleware
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.
- Create API authentication route
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.
- Create API Authentication Controller
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 { /** * 用戶注冊(cè) * * @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); } /** * 獲取用戶詳細(xì)信息 * * @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.
- Testing API Authentication
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 <token>
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" } }
- Summary
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three main ways to set environment variables in PHP: 1. Global configuration through php.ini; 2. Passed through a web server (such as SetEnv of Apache or fastcgi_param of Nginx); 3. Use putenv() function in PHP scripts. Among them, php.ini is suitable for global and infrequently changing configurations, web server configuration is suitable for scenarios that need to be isolated, and putenv() is suitable for temporary variables. Persistence policies include configuration files (such as php.ini or web server configuration), .env files are loaded with dotenv library, and dynamic injection of variables in CI/CD processes. Security management sensitive information should be avoided hard-coded, and it is recommended to use.en

Laravel's configuration cache improves performance by merging all configuration files into a single cache file. Enabling configuration cache in a production environment can reduce I/O operations and file parsing on each request, thereby speeding up configuration loading; 1. It should be enabled when the application is deployed, the configuration is stable and no frequent changes are required; 2. After enabling, modify the configuration, you need to re-run phpartisanconfig:cache to take effect; 3. Avoid using dynamic logic or closures that depend on runtime conditions in the configuration file; 4. When troubleshooting problems, you should first clear the cache, check the .env variables and re-cache.

To enable PHP containers to support automatic construction, the core lies in configuring the continuous integration (CI) process. 1. Use Dockerfile to define the PHP environment, including basic image, extension installation, dependency management and permission settings; 2. Configure CI/CD tools such as GitLabCI, and define the build, test and deployment stages through the .gitlab-ci.yml file to achieve automatic construction, testing and deployment; 3. Integrate test frameworks such as PHPUnit to ensure that tests are automatically run after code changes; 4. Use automated deployment strategies such as Kubernetes to define deployment configuration through the deployment.yaml file; 5. Optimize Dockerfile and adopt multi-stage construction

Laravel's EloquentScopes is a tool that encapsulates common query logic, divided into local scope and global scope. 1. The local scope is defined with a method starting with scope and needs to be called explicitly, such as Post::published(); 2. The global scope is automatically applied to all queries, often used for soft deletion or multi-tenant systems, and the Scope interface needs to be implemented and registered in the model; 3. The scope can be equipped with parameters, such as filtering articles by year or month, and corresponding parameters are passed in when calling; 4. Pay attention to naming specifications, chain calls, temporary disabling and combination expansion when using to improve code clarity and reusability.

User permission management is the core mechanism for realizing product monetization in PHP development. It separates users, roles and permissions through a role-based access control (RBAC) model to achieve flexible permission allocation and management. The specific steps include: 1. Design three tables of users, roles, and permissions and two intermediate tables of user_roles and role_permissions; 2. Implement permission checking methods in the code such as $user->can('edit_post'); 3. Use cache to improve performance; 4. Use permission control to realize product function layering and differentiated services, thereby supporting membership system and pricing strategies; 5. Avoid the permission granularity is too coarse or too fine, and use "investment"

Createahelpers.phpfileinapp/HelperswithcustomfunctionslikeformatPrice,isActiveRoute,andisAdmin.2.Addthefiletothe"files"sectionofcomposer.jsonunderautoload.3.Runcomposerdump-autoloadtomakethefunctionsgloballyavailable.4.Usethehelperfunctions

Select logging method: In the early stage, you can use the built-in error_log() for PHP. After the project is expanded, be sure to switch to mature libraries such as Monolog, support multiple handlers and log levels, and ensure that the log contains timestamps, levels, file line numbers and error details; 2. Design storage structure: A small amount of logs can be stored in files, and if there is a large number of logs, select a database if there is a large number of analysis. Use MySQL/PostgreSQL to structured data. Elasticsearch Kibana is recommended for semi-structured/unstructured. At the same time, it is formulated for backup and regular cleaning strategies; 3. Development and analysis interface: It should have search, filtering, aggregation, and visualization functions. It can be directly integrated into Kibana, or use the PHP framework chart library to develop self-development, focusing on the simplicity and ease of interface.

Create referrals table to record recommendation relationships, including referrals, referrals, recommendation codes and usage time; 2. Define belongsToMany and hasMany relationships in the User model to manage recommendation data; 3. Generate a unique recommendation code when registering (can be implemented through model events); 4. Capture the recommendation code by querying parameters during registration, establish a recommendation relationship after verification and prevent self-recommendation; 5. Trigger the reward mechanism when recommended users complete the specified behavior (subscription order); 6. Generate shareable recommendation links, and use Laravel signature URLs to enhance security; 7. Display recommendation statistics on the dashboard, such as the total number of recommendations and converted numbers; it is necessary to ensure database constraints, sessions or cookies are persisted,
