User Authentication for Web and API with Laravel Fortify and Sanctum
Emmanuel Idoko
Devops Engineer Specializing in Laravel & NestJs | Expertise in Linux & VueJs
In today's world, applications often need to cater to both web and API users. To authenticate these users, a seamless integration of both web and API authentication methods is crucial. In this article, I will be discussing how Laravel Fortify & Sanctum can help achieve this integration.
Laravel Fortify is a headless authentication backend for Laravel that provides various features including cookie-based authentication, two-factor authentication, and email verification. It can be used in combination with Laravel Sanctum to authenticate single-page applications (SPAs) that need to connect with Laravel.
Laravel Sanctum, on the other hand, is a hybrid web/API authentication package that can handle the entire authentication process for your application. It checks if the request includes a session cookie that references an authenticated session or an API token.
The article will be divided into three phases. First, I will demonstrate how to authenticate new users using API authentication. In the third phase, I will show how to achieve the same using web authentication. Join me as I explore the potential of these powerful Laravel packages.
In this phase, 'll walk you through the process of setting up a new Laravel project with Laravel Sanctum and Fortify. Firstly, you need to install a new Laravel project.
composer create-project laravel/laravel web-api-backend
2. Install Laravel Sanctum using the composer package manager:
composer require laravel/sanctum
To complete the installation process, you need to publish the Sanctum configuration and migration files using the following Artisan command:
php artisan vendor:publish -provider="Laravel\Sanctum\SanctumServiceProvider"
Next, run your database migrations to create the API token database table.
php artisan migrate
Add Sanctum's middleware to your api middleware group in the app/Http/Kernel.php file:
For more information, check out the Laravel Sanctum documentation: https://laravel.com/docs/9.x/sanctum
3. Install Fortify using the composer package manager:
composer require laravel/fortify
Publish Fortify's resources using the following vendor:publish command:
php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider"
This command will publish Fortify's actions, the FortifyServiceProvider class, and all necessary database migrations to your app/Actions directory (which will be created if it does not exist).
Next, migrate your database:
php artisan migrate
Ensure that the?App\Providers\FortifyServiceProvider?class is included in the providers array of your?config/app.phpconfiguration file since it is also published when you execute the?vendor:publish?command. The Fortify service provider registers the necessary actions and directs Fortify to use them when executing their respective tasks.
In the fortify configuration file, there is a?features?configuration array that outlines the backend routes and features exposed by Fortify. It is recommended to only enable the basic authentication features, which are shown below.
For more information, check out the Laravel Sanctum documentation: https://laravel.com/docs/9.x/fortify
4. Authentication Routes
Continuing from the previous steps, it's now time to focus on the authentication routes for the API. For the purpose of this phase, we will be working with the routes/api.php file.
First, let's specify the prefix that Fortify will use for all of its registered routes. This can be set in the prefix configuration value within the config/fortify.php configuration file. In this case, we will leave it as an empty string and define it explicitly within the routes/api.php file.
The image below shows the basic endpoint for the authentication routes such as login, register, and forgot-password.
领英推荐
These routes are wrapped in a group with a prefix, which is set in the config/app.php file. To add the API version as prefix, simply modify the config/app.php file and add the following line:
By default, if it is not set in the .env file, the default value will be v1 (version one). To access these routes, a JSON request must be sent with the accept and x-requested-with headers to the API endpoint. To check all available endpoints and routes on your application, simply run the following command:
php artisan route:list
Assuming your base URL is 127.0.0.1:8000, your endpoint URL will be 127.0.0.1:8000/api/v1. This is because we set the api version in the config/app.php file.
It's worth noting that we are taking advantage of the Fortify controllers by using them in our routes/api.php file, streamlining the authentication process and making it easier to manage.
?5. Customising Authentication Responses
Let's dive into customizing the authentication responses in your Fortify service provider. To make modifications, open your app/Providers/FortifyServiceProvider.php file and modify the register method, as shown in the accompanying illustration.
In this file, you will bind implementations of the responses contracts into the Laravel service container. Given that we are utilizing Fortify's authentication logic for both web and API, we will create the user token within the implementations bound in the service container, but not override the register and login methods.
To ensure that the token is created only for json requests, we will include this requirement in the register and login response. To issue the token, you may use the createToken method provided by Fortify. This method returns a Laravel\Sanctum\NewAccessToken instance, which includes a hashed version of the token stored in your database, and a plain-text version of the token accessible through the plainTextToken property. It is recommended to immediately display this value to the user after the token has been created.
6. Email verification?
To ensure a secure and seamless experience for your users, it's important to verify their email addresses after they have registered on your application. To enable this feature, follow these simple steps:
By following these steps, newly registered users will receive an email with a verification link that they must click in order to access the application. However, in order to inform the user that they need to verify their email address, it's important to inform Fortify on how to display the email verification screen or create one for the user when using API endpoints.
7. Resend Verification Email
To customize the email verification process, we can add a verification notification route within the routes/api.php file;
Then we create a new controller within the App\Http\Controllers\EmailVerificationNotificationController.php file and make the necessary modifications. Remember to import this file in. your?routes/api.php file.
In the controller, we extend the Fortify EmailVerificationNotificationController and override the store method to return our custom email response. This customization allows us to provide a tailored experience for the users and make the email verification process more seamless and user-friendly.
By following these steps, we can enhance the email verification process and provide a better overall experience for our users.
8. Testing
To conclude, it is important to test the authentication process to ensure it is functioning as expected. First, we'll perform a registration and verify the registration was successful.
After the registration, we'll receive a token and an email verification link will be sent to the user.?In the next phase I will show you how to verify your email address by clicking on the link sent, for now, you can manually verify the user. After email verification, we can then make another request to the https://127.0.0.1:8000/api/v1/user endpoint to test if it returns the correct authenticated user. It is important to include the header "Authorization" with the "Bearer" token in the request.
In case the initial email verification link did not go through, you can resend the email by making a request to the email verification notification endpoint with the corresponding token.
In conclusion, the customisation of authentication responses in Laravel provides a lot of flexibility for developers to shape the way authentication is done within their applications. By leveraging the power of Laravel Fortify and its Service Providers, developers can easily implement custom responses for registration and login endpoints, email verification, and even handle the creation of tokens for authenticated users. The article demonstrated how to carry out these customizations and also provided steps to test if the custom responses have been properly implemented. By following these steps, developers can create a more robust and secure authentication system for their applications. In case the initial email verification link did not go through, you can resend the email by making a request to the email verification notification endpoint with the corresponding token.