DEV Community

loading...
Cover image for Two Factor Authentication using NodeJs

Two Factor Authentication using NodeJs

akarshbarar profile image Codecave ・2 min read

If you have ever dealt with authentication in your application then you must have seen two factor authentication where you have to give a token or code that might be send to you by SMS or email. So lets build something like that and learn two factor authentication.
Before learning two factor authentication lets understand pros and cons of 2FA(2 Factor Authentication)

Pros of 2FA

  1. Provides Security to application.
  2. Easy to setup

Cons of 2FA

  1. Involves sharing of Email or Phone number
  2. Prone to MIM attack

Let's Get Started

=> Create a node project

  __ npm init -y __
Enter fullscreen mode Exit fullscreen mode

=> Lets install some dependencies

  __ npm install express node-json-db uuid speakeasy __
Enter fullscreen mode Exit fullscreen mode

=> Create a simple Express app

Alt Text
=> Firstly create database here I am Node JSON database you can use any database that you want.
Alt Text
=> Now register the user and create a temporary secret for him.
Alt Text
=> When you will register the user you will get a secret key and token
that will look like this in base32
Alt Text
But you can also go with simple key and it will look like this
Alt Text
=> Now lets verify the user for that you need things one is the userId the user who is trying to login and one is the token this is token is generated in many ways you can use chrome extension that taken secret key from the register process and gives you a token or you can also use mobile apps I am using extension to generate token.
Alt Text

if it return verified true then you are good to go otherwise no.

you can also go one step further to validate the token.

Alt Text

if it return validate true then you are good to go otherwise no.

Github repo of above is:

[https://github.com/akarshbarar/TwoFactorAuthentication)


Follow me on Github
Follow me on Instagram
Follow me on Twitter


--------------------THANK YOU------------------------

Discussion

pic
Editor guide