Laravel API Authentication
What is API authentication in Laravel?
API authentication in Laravel is the process of verifying the identity of users or clients before allowing them to access API routes or resources. This ensures that only authorized users can interact with the API. Laravel provides various ways to authenticate users for APIs, such as Laravel Sanctum, Passport, or token-based authentication.
What is Laravel Sanctum?
Laravel Sanctum is a lightweight authentication package that allows you to issue API tokens to users without the complexity of OAuth. It is suitable for both single-page applications (SPAs) and simple token-based APIs. Sanctum provides a secure and easy way to authenticate API requests and offers token management features.
Example of installing Laravel Sanctum:
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
After installation, you can use Sanctum to protect your API routes with token-based authentication.
How do you issue an API token using Laravel Sanctum?
In Laravel Sanctum, you can issue API tokens to users using the createToken()
method on the user model. This generates a personal access token that the user can use to authenticate API requests.
Example of issuing an API token:
use App\Models\User;
public function login(Request $request)
{
$user = User::where('email', $request->email)->first();
if ($user && Hash::check($request->password, $user->password)) {
$token = $user->createToken('API Token')->plainTextToken;
return response()->json(['token' => $token], 200);
}
return response()->json(['error' => 'Invalid credentials'], 401);
}
In this example, after successful authentication, an API token is generated and returned to the user.
How do you protect API routes using Sanctum in Laravel?
To protect API routes using Sanctum, you apply the auth:sanctum
middleware to the routes that require authentication. This ensures that only users with valid API tokens can access these routes.
Example of protecting API routes:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
In this example, the /user
route is protected, and only authenticated users with valid API tokens can access it.
How do you authenticate API requests using Sanctum tokens?
To authenticate an API request using Sanctum, the client needs to include the API token in the Authorization
header of the request. The token is sent as a Bearer token.
Example of authenticating an API request:
GET /user
Authorization: Bearer {API_TOKEN}
In this example, the API token is passed in the Authorization
header, and the request will be authenticated if the token is valid.
What is Laravel Passport?
Laravel Passport is a full OAuth2 server implementation for Laravel applications. It provides a complete solution for API authentication, including issuing access tokens, refresh tokens, and managing client credentials. Passport is suitable for applications that require advanced OAuth2 features like third-party authentication.
Example of installing Laravel Passport:
composer require laravel/passport
php artisan migrate
php artisan passport:install
After installation, Passport provides a full OAuth2 server that can handle various types of API authentication.
How do you protect API routes using Laravel Passport?
To protect API routes using Laravel Passport, you apply the auth:api
middleware to the routes that require OAuth authentication. This ensures that only users with valid OAuth access tokens can access these routes.
Example of protecting API routes with Passport:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
In this example, the /user
route is protected by OAuth2 authentication using Passport.
What is the difference between Laravel Sanctum and Passport?
The key differences between Laravel Sanctum and Passport are:
- Laravel Sanctum: Simplified token-based authentication, suitable for single-page applications (SPAs) and simple APIs. It does not provide full OAuth2 features like Passport.
- Laravel Passport: Full OAuth2 server implementation with advanced features like authorization codes, client credentials, and refresh tokens. It is ideal for complex authentication flows or third-party API access.
How do you revoke API tokens in Laravel Sanctum?
You can revoke a user's API token by deleting the token instance. Laravel Sanctum provides methods to revoke a single token or all tokens associated with the user.
Example of revoking a single token:
$user->tokens()->where('id', $tokenId)->delete();
Example of revoking all tokens:
$user->tokens()->delete();
In these examples, you can revoke tokens by deleting them from the database.
How do you use token abilities in Laravel Sanctum?
Sanctum allows you to assign abilities (permissions) to tokens to control what actions the token can perform. You can define abilities when creating a token and check for these abilities during authentication.
Example of assigning abilities to a token:
$token = $user->createToken('API Token', ['create-post', 'delete-post'])->plainTextToken;
Example of checking abilities during authentication:
if ($request->user()->tokenCan('create-post')) {
// The token has the ability to create posts
}
In this example, the token is checked for the ability to create posts before performing the action.
How do you refresh tokens in Laravel Passport?
Laravel Passport supports the OAuth2 refresh token flow, which allows users to obtain a new access token using a refresh token without having to log in again.
Example of refreshing a token using Passport:
POST /oauth/token
Content-Type: application/json
{
"grant_type": "refresh_token",
"refresh_token": "{REFRESH_TOKEN}",
"client_id": "{CLIENT_ID}",
"client_secret": "{CLIENT_SECRET}"
}
In this example, a new access token is generated using the refresh token provided by the client.
How do you use personal access tokens with Laravel Passport?
Laravel Passport allows users to generate personal access tokens, which can be used to authenticate API requests. These tokens are similar to those generated by Sanctum but offer more flexibility with Passport's OAuth2 features.
Example of generating a personal access token:
$token = $user->createToken('Personal Access Token')->accessToken;
This token can then be used to authenticate API requests by including it in the Authorization
header.
How do you implement multi-authentication for APIs in Laravel?
Laravel allows you to implement multi-authentication by using different guards for various user types (e.g., users, admins). Each guard can be configured to use different authentication methods or tokens, making it possible to handle multiple types of users in the same API.
Example of defining multiple guards in config/auth.php
:
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
'admin-api' => [
'driver' => 'passport',
'provider' => 'admins',
],
],
In this example, two guards are defined: one for regular users and one for admins, allowing for different authentication flows.