Authentication with Laravel OTP
Nowadays most web applications prefer to use OTP(One-Time Password) instead of using username/password which was a classic authentication system to validate users. Because, this way is more secure and in contrast to static passwords, they are not vulnerable to replay attacks.
Maybe you are also worried about implementing a one-time password as a web developer in the Laravel framework.
There are many concerns about that such as :
- How can I generate a secure token?
- Where should I store generated token?
- Is token valid or not? Is token expired or not?
- How can I have an integrated and also usable system for different user providers?
- etc…
Well, good news! We have just released a package to resolve your concerns. Here you are. This is Laravel OTP package.
Let’s start a practical implementation step by step.
Getting started
First, you should install OTP package via composer:
composer require fouladgar/laravel-otp
Then, publish config/otp.php
file by running:
php artisan vendor:publish --provider="Fouladgar\OTP\ServiceProvider" --tag="config"
And Finally migrate the database:
php artisan migrate
Model Preparation
As next step, make sure the user model implement Fouladgar\OTP\Contracts\OTPNotifiable
and also use Fouladgar\OTP\Concerns\HasOTPNotify
trait:
SMS Client
There is a default OTPSMSChannel
which needs a SMS client for sending generated token to the user mobile phone. So, you should specify your SMS client and implement Fouladgar\OTP\Contracts\SMSClient
contract. This contract requires you to implement sendMessage
method.
This method will return your SMS service API results via a Fouladgar\OTP\Notifications\Messages\MessagePayload
object which contains user mobile and token message:
Next, you should set the client wrapper SampleSMSClient
class in config/otp.php
file:
It’s almost over…
Setup Routes and Controller
We need some routes to send and validate the token. Let’s make them and implement our controller.
You may add those in the web
or api
routes. It depends on you want to use OTP as Full Stack or API Back-End. It’s up to you. In this article I prefer use the second way.
Well, open the routes/api.php
and put this routes:
And then create a AuthController.php
class like this:
Finish. Now, you can call the routes like below:
// send otp request
curl --request POST \
--url http://localhost/api/send-otp \
--data '{
"mobile" : "09389599530"
}'// validate otp request
curl --request POST \
--url http://localhost:8585/api/validate-otp \
--data '{
"mobile" : "09389599530",
"token" : "94352"
}'
That’s it.
For more details, please check out the documentation in GitHub:
Hope to useful this package. I’m waiting your opinions and comments.
Thank you for sharing your valuable time with me.