How to implement Two-Factor Authentication using Next.js, Twilio and Altogic



Introduction

This text will cowl two-factor authentication fundamentals utilizing Next.js, Twilio, and Altogic, a Backend-as-a-Service platform utilizing its consumer library. This authentication technique permits customers so as to add yet one more safety layer to their software. Many individuals allow their two-factor authentication settings to extend their safety utilizing their cellphone numbers or authentication apps for safety functions.

You possibly can try the source code and demo app.



How is the two-factor authentication circulate?

  1. Customers who have already got an account have to set their cellphone quantity to allow two-factor authentication.

  2. An SMS with a code is distributed to the required cellphone quantity by Altogic and Twilio.

  3. Customers confirm their cellphone quantity by coming into the code despatched to their cellphone quantity.

  4. Customers can allow or disable the two-factor authentication setting from their profile.

  5. When customers attempt to register, if two-factor authentication is enabled, a code is distributed to the required cellphone quantity by Altogic and Twilio.

  6. Customers confirm their identification by coming into the code on the enter on the display.

  7. If two-factor authentication will not be enabled, they’ll register with out this course of.



Youtube Showcase Video




Arrange the Venture

This venture builds on prime of the whole e-mail authentication app we created beforehand. You possibly can observe the tutorial to construct the identical app or clone the venture from here and proceed with the remainder of the tutorial.



Twilio Integration

You want to enroll in Twilio with a free/paid trial. You want to get the Account SID and Auth Token for integration with Altogic Consumer Library.

Should you use the free trial, you have to to take the Twilio cellphone quantity to ship SMS messages to the customers.

  1. Create an Account on Twilio

  2. Open Console

  3. Click on “Get a trial cellphone quantity” on the left-top of the Console

  4. Copy Account SID, Auth Token, and My Twilio cellphone quantity values to the clipboard

Now, we’ve copied the configuration credentials to the clipboard. You should specify the verified cellphone numbers in trial accounts, which we outlined as “ to quantity” in Altogic.

  1. Click on on the Discover Merchandise within the left sidebar.

  2. Make sure that Messaging and Telephone Numbers merchandise are chosen.

Now you’ll be able to navigate to the Verified Caller IDs web page by Sidebar → Telephone Numbers → Handle → Verified Caller IDs.

You need to add your cellphone quantity as a Verified Caller from right here.

And at last, you must give geo permission to your cellphone numbers area. You possibly can go to this web page by SidebarMessagingSettingsGeo permissions.



Create the fashions

Fashions outline the knowledge construction and knowledge validation guidelines of your purposes. A mannequin consists of fundamental, superior, and sub-model fields. As an analogy, you’ll be able to consider fashions as tables and fields as columns in relational databases or fashions as paperwork and fields as doc properties in non-relational databases.

Key entities in Altogic

Once we create our software, a consumer mannequin is created by default. We have to add a boolean area to this consumer mannequin to let customers allow and disable the two-factor authentication.

To create a area through the Designer, you’ll want to Navigate to Fashions view and choose the mannequin you want to add the brand new area. You may be directed to the mannequin particulars view.

  1. Within the mannequin particulars view, choose New area.

  2. From the dropdown menu, choose the Boolean that you simply want to create.

  3. Within the area title, kind “twoFactorAuth” and set a default worth of false

  4. Choose Create

We have to create a brand new mannequin known as phoneVerificationCode to deal with the verification code we ship to customers’ cellphone numbers. This knowledge kind shall be a Transient knowledge kind which means it isn’t saved within the database. We’re defining it as Transient as a result of we don’t want it after finishing the verification.

To create a mannequin through the Designer, you may have two choices. You possibly can both create a mannequin from scratch or a pattern JSON doc. In both case, first, you’ll want to navigate to the Fashions view in designer and choose +New.

After, you’ll be able to decide a Mannequin.

And create the phoneVerificationCode mannequin. Afterward, we have to add three fields:

  1. code area, which is an Integer.

  2. userId area, which is an Object reference to the customers mannequin.

  3. phoneNumber area, which is a Textual content area.



Create the endpoints

Endpoints are the communication channels to entry the companies supplied in your purposes, and thru endpoints, you expose your software companies and knowledge to the surface world.

To create an endpoint through the Designer, you’ll want to navigate the Endpoints view in designer and choose New->Endpoint.

How to create endpoints in Altogic Designer

After clicking, you’ll want to enter a related endpoint title and optionally decide a bunch, decide a way, specify the trail and assign a service that handles the requests to the endpoint.

We will additionally click on on the “Session required” checkbox, which enforces a necessity for a session when a request is made to the endpoint.

On this instance, our technique is “POST,” and our path is “/customers/set-phone” which means that if we ship a POST request to this path, the service we outline will run. We created a service by clicking “Add new service” and by naming our service, we shall be created an empty service. We are going to design the service subsequent.

We are going to create three extra endpoints to confirm the code whereas altering the cellphone, signing in, and implementing the actual sign-in performance.

Create the confirm code throughout altering cellphone endpoint:

Verify code during changing phone endpoint

Create the confirm code in the course of the sign-in endpoint:

Verify code during sign-in endpoint

Create the sign-in endpoint for implementing the actual 2-FA logic:

Sign in endpoint for implementing the specific 2-FA logic

Now that we created our endpoints and companies, we are able to begin designing the companies, which is the most enjoyable half of utilizing Altogic!



Design the Companies

Constructing the circulate of service entails three principal actions.

  1. Including the best node from the nodes library to the service circulate space.

  2. Customizing the added node parameters utilizing the node properties panel.

  3. Linking the output hyperlink level of a node to the enter hyperlink level of one other node utilizing relations.

First, we are going to implement the “Set cellphone quantity service.” Now we have the beginning node, which is used to begin the execution of the endpoint dealing with service. It runs solely as soon as at first of the service to set off nodes linked to its output hyperlink level. We outline a question string parameter of kind textual content named “phoneNumber” as enter for this endpoint.

Then, we verify if the cellphone quantity despatched is a legitimate cellphone quantity with the ISMOBILEPHONE() perform.

If no, return an error response.

If sure, create an object of phoneVerificationCode mannequin. For code, we generate a random quantity with RANDBETWEEN() perform and insert the opposite fields from both the enter or the session.

Cache the article we created so we are able to entry it later for verifying the code. I need the code to run out after one minute, so I set the timeout worth to 1 minute.

Ship the SMS message to the required cellphone quantity with the code. Right here we use the Twilio credentials we obtained.

Then we return the success response. That is the ultimate look of our service:

Subsequent, we are going to implement the “Confirm code in change cellphone service.” This service is used to confirm the code when customers wish to change their cellphone numbers.

Now we have the beginning node, which is used to begin the execution of the endpoint dealing with service. It runs solely as soon as at first of the service to set off nodes linked to its output hyperlink level. We outline the request physique construction as a single mannequin of “phoneVerificationCode” as enter for this endpoint.

Get the cached object with the cellphone quantity to verify the code.

Return an error response if the cached object doesn’t exist anymore. It signifies that the code is expired and not legitimate.

Examine if the cached code is equal to the code despatched within the “phoneVerificationCode” object.

Replace the consumer’s cellphone quantity and set the “phoneVerified” to true utilizing the “Replace Object Fields by Id” node. We have to set the up to date object mannequin to “customers” and object id to the userId, and we try this by giving the userId we receive from phoneVerificationCode object.

Then we return the success response. That is the ultimate look of our service:

Subsequent, we are going to implement the “Confirm code in sign-in service.” This service is used to confirm the code when customers attempt to register when their two-factor authentication is enabled.

Now we have the beginning node, which is used to begin the execution of the endpoint dealing with service. It runs solely as soon as at first of the service to set off nodes linked to its output hyperlink level. We outline the request physique construction as a single mannequin of “phoneVerificationCode” as enter for this endpoint.

Get the cached object with the cellphone quantity to verify the code.

Return an error response if the cached object doesn’t exist anymore. It signifies that the code is expired and not legitimate.

Examine if the cached code is equal to the code despatched within the “phoneVerificationCode” object.

Return error if code will not be equal to the one despatched within the enter.

Get the consumer utilizing the “Get Single Object by Question” node. We have to set the retrieved object mannequin to customers, and our question ought to be this.cellphone==inputObject.phoneNumber to get the consumer with the required cellphone.

If there isn’t a consumer, return an error response.

If there’s a consumer, create a consumer session.

Then we return the success response. That is the ultimate look of our service:

Subsequent, we are going to implement the “Register service.” This service is used to implement the sign-in function. As a result of we wish to use two-factor authentication, we are able to’t use the perform within the consumer library, and now we have to design it ourselves. However don’t fear, designing advanced enterprise logic in Altogic is comparatively straightforward! 🙂

Now we have the beginning node, which is used to begin the execution of the endpoint dealing with service. It runs solely as soon as at first of the service to set off nodes linked to its output hyperlink level. We outline a question string parameter of kind e-mail named “e-mail” and kind textual content known as “password” as enter for this endpoint.

Get the consumer utilizing the “Get Single Object by Question” node. We have to set the retrieved object mannequin to customers, and our question ought to be this.e-mail==params.physique.e-mail to get the consumer with the required e-mail.

Return an error if there isn’t a consumer with the required e-mail.

Use the “If-Else Situation” node to verify if the emailVerified area of the consumer is true or not.

If the e-mail will not be verified, return an error response.

Evaluate the password despatched with the password within the database with ECOMPARE() perform. This perform compares the password textual content within the enter with the password within the database however doesn’t expose the encrypted password. Nobody, together with the developer, can see the consumer’s passwords.

Return an error response if passwords don’t match.

Examine if the two-factor authentication of the consumer is enabled.

If two-factor authentication of the consumer will not be enabled, create the consumer session and return it with the consumer knowledge.

If enabled, create an object of phoneVerificationCode mannequin. For code, we generate a random quantity with RANDBETWEEN() perform and insert the opposite fields from the enter.

Cache the article we created so we are able to entry it later for verifying the code. I need the code to run out after one minute, so I set the timeout worth to 1 minute.

Ship the SMS message to the required cellphone quantity with the code. Right here we use the Twilio credentials we obtained.

Then we return the success response. That is the ultimate look of our service:

To study extra about constructing the service flows, try the documentation.



Let’s Begin Coding!



Set/Change cellphone performance

To allow two-factor authentication, customers have to arrange their cellphone numbers. This performance is identical as altering the cellphone performance so that we are going to use the identical display with some minor conditional UI modifications.

Now we have already created the endpoint and designed the service. We have to ship a request to the endpoint utilizing Altogic Consumer Library utilizing EndpointManager and the publish technique like altogic.endpoint.publish()



SMS confirm throughout change cellphone performance

Code above runs the service for setting/altering the cellphone quantity and sending the SMS for verification code. Now, customers want a display to enter the SMS code. Now we have already created the endpoint and designed the service for this case. We have to ship a request to that individual endpoint.

Right here is the code for that:



Toggle Two Issue Authentication performance

Customers ought to be capable to change on and off two-factor authentication in the event that they wish to. For this, we’re implementing a fundamental change. We’re updating the twoFactorAuth boolean area.



Register performance

When customers wish to register, we are going to use the service we designed as a result of we have to verify if two-factor authentication is enabled and if sure, we have to ship an SMS with a code. We exchange the consumer library perform with sending a request to the endpoint.



SMS confirm throughout sign-in performance

Code above runs the service for signing in and sending the SMS for verification code. Now, customers want a display to enter the SMS code. Now we have already created the endpoint and designed the service for this case. We have to ship a request to that individual endpoint with code, cellphone quantity, and userId.

Right here is the code for that:



Conclusion

This text lined including the two-factor authentication technique to our e-mail authentication app utilizing Next.js, Twilio, and Altogic Client Library. Because of Altogic, we are able to construct this performance with just some traces of code.

You possibly can try the GitHub repository for different functionalities and the remainder of the code. You too can clone it and construct your app on prime of it.

Add a Comment

Your email address will not be published. Required fields are marked *