Sitemap
Akarsh Barar

Akarsh Barar

CodeToCompete

Two Factor authentication using NodeJs

3 min readNov 12, 2020

--

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

=> Lets install some dependencies

npm install express node-json-db uuid speakeasy

=> Create a simple Express app

Press enter or click to view image in full size

=> Firstly create database here I am Node JSON database you can use any database that you want.

Press enter or click to view image in full size

=> Now register the user and create a temporary secret for him.

Press enter or click to view image in full size

=> When you will register the user you will get a secret key and token
that will look like this in base32

Press enter or click to view image in full size

But you can also go with simple key and it will look like this

Press enter or click to view image in full size

=> 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.

Press enter or click to view image in full size

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

Get Akarsh Barar’s stories in your inbox

Join Medium for free to get updates from this writer.

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

Press enter or click to view image in full size

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](https://github.com/akarshbarar)
Follow me on [Instagram](https://www.instagram.com/mycodecave/)
Follow me on [Twitter](https://twitter.com/CodeCave2)

— — — — — — — — — — — — — — — — — — — — — — — — — — -

— — — — — — — — — — THANK YOU — — — — — — — — — — — —

--

--