Phone Number Authentication (OTP) with Firebase in Laravel 8

Phone Number Authentication (OTP) with Firebase in Laravel 8

Admin
Admin・ 10 Agustus 2021
9 min read ・ 3305 views

Laravel Firebase Authentication - Phone number authentication or telephone number authentication is one of the many ways that is done or implemented in a system or application to determine the authenticity of the phone number entered by the user during registration. There are lots of providers that we can use to create phone number authentication or OTP, one of which is Firebase.

Well, in this tutorial we will try to implement a service from firebase to generate or send an OTP code to the telephone number that has been inputted. We will implement Firebase Authentication in Laravel version 8. Maybe in this experiment we will only try to send OTP codes via SMS, without any authentication logic in Laravel 8. If you want to implement this firebase authentication feature in Laravel features such as the register feature, please can improve from the examples that will be given in this tutorial.

Register Firebase Account

register firebase account

The first step we have to do is register a firebase account with a gmail email. Then next we will be directed to the console page, on this console page please create a new project by clicking Add project.

Link: https://firebase.google.com

create firebase project

Here I will give an example by creating a new project with the name Laravel OTP Authentication, then click Continue.

get firebase code

After successfully creating the project, we will be directed to our firebase project dashboard page. On this page, please click the markup icon to get the credentials that we will use in the project practice creating phone number authentication with firebase in laravel 8.

register firebase app

Before we get the firebase credentials, there is a step we must go through first, namely registering the app. In this step we will register the app to add firebase to our web application. For example, here I will register an app with the name Laravel OTP Authentication and continue by clicking Register app.

firebase SDK

OK, after going through the app register process, we have managed to get the scripts along with our firebase project credentials that we will use in this project exercise. Then click the Continue to Console button.

*Save this script.

firebase authentication

Then we need to enable firebase authentication in our laravel project. Please open the firebase console dashboard, then click card authentication as shown above.

enable sign in method

On the authentication page, navigate to the nav tab Sign-in Method, then to sign in the phone provider select Enable.

Install Laravel 8

composer create-project laravel/laravel laravel-otp-authentication
cd laravel-otp-authentication

After successfully registering firebase and creating project in the previous step, now let's start coding starting with installing the laravel version (currently version 8). Please open a terminal, then run the command as above. This command will create a laravel project folder with the name laravel-otp-authentication. If the installation process is complete, please enter the project with the command cd laravel-otp-authentication.

Setup Blade View

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel 8 Firebase - Phone Number OTP Authentication</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    </head>
    <body>
        <div class="container mt-5">
            <div class="row">
                <div class="col-6">
                    <div class="card">
                        <div class="card-header">Add Phone Number</div>
                        <div class="card-body">
                            <div class="alert alert-danger" id="error" style="display: none;"></div>
                            <div class="alert alert-success" id="successAuth" style="display: none;"></div>
                            <form>
                                <input type="text" id="number" class="form-control" placeholder="+62 ********">
                                <div id="recaptcha-container" class="mt-2"></div>
                                <button type="button" class="btn btn-primary mt-3" onclick="sendOTP();">Send OTP</button>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="col-6">
                    <div class="card">
                        <div class="card-header">Add verification code</div>
                        <div class="card-body">
                            <div class="alert alert-success" id="successOtpAuth" style="display: none;"></div>
                            <form>
                                <input type="text" id="verification" class="form-control" placeholder="Verification code">
                                <button type="button" class="btn btn-success mt-3" onclick="verify()">Verify code</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
        <script src="https://www.gstatic.com/firebasejs/6.0.2/firebase.js"></script>
        <script>
            var firebaseConfig = {
            apiKey: "YOUR API KEY",
            authDomain: "YOUR AUTH DOMAIN",
            projectId: "YOUR PROJECT ID",
            storageBucket: "laravel-otp-authentication.appspot.com",
            messagingSenderId: "515983180172",
            appId: "YOUR APP ID"
            };
            firebase.initializeApp(firebaseConfig);
        </script>
        <script type="text/javascript">
            window.onload = function () {
                render();
            };
            
            function render() {
                window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
                recaptchaVerifier.render();
            }
            
            function sendOTP() {
                var number = $("#number").val();
                firebase.auth().signInWithPhoneNumber(number, window.recaptchaVerifier).then(function (confirmationResult) {
                    window.confirmationResult = confirmationResult;
                    coderesult = confirmationResult;
                    console.log(coderesult);
                    $("#successAuth").text("Message sent");
                    $("#successAuth").show();
                }).catch(function (error) {
                    $("#error").text(error.message);
                    $("#error").show();
                });
            }
            
            function verify() {
                var code = $("#verification").val();
                coderesult.confirm(code).then(function (result) {
                    var user = result.user;
                    console.log(user);
                    $("#successOtpAuth").text("Auth is successful");
                    $("#successOtpAuth").show();
                }).catch(function (error) {
                    $("#error").text(error.message);
                    $("#error").show();
                });
            }
        </script>
    </body>
</html>

We proceed to the blade view setup step. In this step we will edit the welcome.blade.php file. Please copy all the code above and replace it in the welcome.blade.php file. With the code above we will create two cards, each of which has a function to input a telephone number and send the OTP code via SMS to the inputted phone number and the second card has a function to input the OTP code it receives via SMS.

In the add phone number card we also add google recaptcha to provide security.

In this welcome.blade.php file we will use CSS from bootstrap version 5 and jQuery and Firebase scripts to create a function that will handle phone number authentication or send OTP code from Firebase.

In the firebase script, please adjust the apiKey, authDomain, projectId, storageBucket, messagingSenderId and appId values ​​with the firebase SDK script that we got when registering the firebase app in the first step.

Firebase Phone Number Authentication (OTP) testing

laravel 8 firebase phone number authentication (OTP)

After going through several processes starting from registering firebase accounts, creating projects, adding apps, installing laravel to setting up blade view, it's time for us to test. Please run the server with php artisan serve, then open the project in a browser with URL 127.0.0.1:8000 or laravel-otp-authentication.test. On the root page of our Laravel project, it will display as shown above. Please try adding a phone number complete with country code (such as +62) and complete the google recaptcha challenge then click Send OTP. After clicking the Send OTP button, Firebase will send an SMS OTP code to the entered telephone number.

firebase authorized domain

If when you click the Send OTP button, the error "Hostname match not found" appears, it means that we need to add data in the Authorized Domain. To add a domain, please go to console>Authentication>Sign-in Method scroll down in the Authorized Domain section and add our laravel project domain like 127.0.0.1 or laravel-otp-authentication.test.

otp code laravel 8 firebase

An example of an SMS OTP code that was successfully sent by Firebase to our telephone number can be seen as shown in the image above.

firebase sms verification template

The SMS text message OTP code is obtained from Authentication>Templates as shown above.

So far, we have succeeded in making the phone number authentication feature by sending an OTP code using the authentication service from firebase in the Laravel project version 8. Hopefully this tutorial article can be useful or helpful and see you in the next article.

 

Doc: Firebase Phone Number Authentication 

Credit: User illustrations by Storyset

Tinggalkan Komentar
Loading Comments