Home > Article > PHP Framework > Laravel development: How to implement API authentication and authorization using Laravel Sanctum?
Laravel is a popular PHP web development framework that provides many powerful features and tools to simplify the development and maintenance of web applications. Laravel Sanctum is a plugin for the Laravel framework that provides API authentication and authorization capabilities to easily protect your API endpoints from unauthorized access.
In this article, we will learn how to implement API authentication and authorization using Laravel Sanctum.
1. What is Laravel Sanctum?
Laravel Sanctum is a lightweight authentication package that provides simple but powerful API authentication and authorization functionality. It is based on Laravel middleware and HTTP authentication, allowing us to securely attach authentication tokens to API requests.
Laravel Sanctum supports two authentication methods: Cookie-based authentication and Token-based authentication. Cookie-based authentication uses Laravel middleware to verify that a valid authentication cookie is present in the request. Another way to verify the Token in the Header class and check if it is valid.
2. Install Laravel Sanctum
Before we begin, we need to install Laravel Sanctum first. Laravel Sanctum can be easily installed using the composer package manager:
composer require laravel/sanctum
Of course, it can also be installed manually by adding the following requirements in the composer.json file:
{ "require": { "laravel/sanctum": "^2.9" } }
Once completed, run the following Command to publish Laravel Sanctum configuration files and database migration files:
php artisan vendor:publish --tag=sanctum-config php artisan vendor:publish --tag=sanctum-migrations php artisan migrate
3. Configure Laravel Sanctum
Modify the app/Http/kernel.php file and add the Sanctum middleware:
// app/Http/Kernel.php protected $middleware = [ // ... LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class, ]; protected $middlewareGroups = [ 'web' => [ // ... ], 'api' => [ LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class, 'throttle:api', IlluminateRoutingMiddlewareSubstituteBindings::class, ], ];
This will ensure that Sanctum's cookie-based authentication can be used during every request.
Open the config/auth.php file, find defaults and guards and configure them to use sanctum.
// config/auth.php 'defaults' => [ 'guard' => 'api', 'passwords' => 'users', ], 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'sanctum', 'provider' => 'users', 'hash' => false, ], ],
This will allow us to use Sanctum for token based authentication.
If you are using a new version of Laravel, you do not need to add a provider. If you are using an older version, please open the config/app.php file and add the following lines in the providers array:
LaravelSanctumSanctumServiceProvider::class,
IV. Create Authorization Token
Now, we have configured Laravel Sanctum, next we will learn how to use Sanctum to create authorization tokens.
public function createToken(Request $request) { $user = Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')]); if($user) { $token = $user->createToken('API Token')->plainTextToken; return response()->json([ 'token' => $token, ]); } else { return response()->json([ 'message' => 'Invalid credentials', ], 401); } }
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
5. Implement API authentication and authorization
After creating the authorization token, we can use Sanctum to protect the API endpoint from Unauthorized access. We can use Laravel routing middleware to check the authentication token and deny unauthorized access.
// routes/api.php Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); });
This route will be protected using the Sanctum auth middleware.
php artisan serve
Now, the /api/user route can be accessed to view the details of the logged in user. Now, without the Authorization header, you won't be able to access it and will return a 401 Unauthorized HTTP status code.
6. Ending
Laravel Sanctum is a powerful and easy-to-use authentication and authorization solution that can easily implement authentication and authorization in Laravel web applications and web APIs. It easily protects your API endpoints from unauthorized access and allows you to easily control which users can access which API endpoints. In this article, we learned how to install and configure Laravel Sanctum and saw how to use it to create authorization tokens and implement API authentication and authorization.
The above is the detailed content of Laravel development: How to implement API authentication and authorization using Laravel Sanctum?. For more information, please follow other related articles on the PHP Chinese website!