Route Protection & 3rd Party Authentication.

Ankit_Singh_Wakefit
3 min readMar 1, 2020

--

Route protection using Jsonwebtoken, cookie-session, and Third-party login.

We know our front-end can interact with a server using HTTP requests which are binary information packets that a computer or client sends to another computer or server to communicate But here comes the problem as HTTP requests are stateless means each Http request for a server is fresh and has no connection with the previous request.

So for the server, all the Http requests are fresh and independent thus the client can visit any route. To overcome this problem we can use cookie-session or JSON web token or 3rd party login using other websites like Google, Facebook, Twitter, etc. let's see Jsonwebtoken first.

“JSON Web Tokens are an open, industry-standard RFC 7519 method for representing claims securely between two parties.”

JSON web tokens are text strings that can be used by the client and servers to authenticate and share information easily and this information is encoded as well as encrypted so are safe. JWTs basically consists of three parts separated by a ‘.’ These are the header, payload, and signature. A JWT typically looks like the following.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

aaa.bbb.ccc

aaa is the header part that contains info like Algorithm and token type which may look like

{
“alg”: “HS256”,
“typ”: “JWT”
}

bbb is the payload part where we store data related to a client for authentication purposes. Data like username, email or unique Id which may look like

{
“id”: “1234567890”,
“name”: “John Doe”,
“iat”: 1516239022
}

ccc is the signature part that is used to encrypt our information and generate taken, we have covered a lot of theory parts now let's drive into the coding part. To use JWT we would first install express and JSON web token library.

npm i express jsonwebtoken mongoose bcryptjs

we will also discuss about mongoose and bcryptjs in some time but first, let’s focus on the JSON web token.

var jwt = require('jsonwebtoken');

jwt.sign(payload, secret, callback => {})

we generate a token using payload and the secret key and we have already discussed about them and with every request, we will send this generated token and once the token has been sent to the client, its the client's responsibility to store the token somewhere either in localStorage or cookies. so our code looks like this —

jwt.sign({userId: user._id, "thisisasecret", (err, token) => {
// send the token to client
res.json({ token });
}})

Now for each resource that is protected on the server, the client has to send the request along with token present in request headers. Once a request is made using token we can verify the token using verify method that is predefined.

jwt.verify(token, secret, (err, payload) => {
if(err) // invalid token
// token is validated, proceed to next request
})

So if a client wants to use protected information or to perform certain tasks that only a login user can perform have to send the token with each request. on the server-side, we use middleware before all protected routes and middleware looks like this —

const validateToken = (req, res, next) => {
var token = req.headers.authorization;
if(token) {
// use same secret used while generating token
jwt.verify(token, secret, (err, payload) => {
// error if token has been tempered
if(err) return res.status(400).json({ err })
// put payload info into request and allow request to proceed by calling next
req.user = payload;
next();
})
} else {
res.status(401).json({ error: 'token is required' })
}

}

We will see other parts like 3rd party login in part 2 as this article is already very long. See you all in the next part.

--

--