Hey!!
Let's start the learning process in easy way without wasting time
1. Difference between Authentication and Authorization??
Before moving on, let's first understand the difference between Authentication and Authorization
Both Authentication and Authorization area unit utilized in respect of knowledge security that permits the safety on an automatic data system
In authentication process, the identity of users are checked for providing the access to the system. While in authorization process, person’s or user’s authorities are checked for accessing the resources. Authentication is done before the authorization process, whereas authorization process is done after the authentication process.
2. What is JWT??
JWT (Json Web Token) is another npm package just like express,bodyparser etc and used for authentication and authorisation.
JWTs are mainly used for authentication. After a user signs in to an application, the application then assigns JWT (token/ticket) to that user. Subsequent requests by the user will include the assigned JWT. This token tells the server what routes, services, and resources the user is allowed to access.
For ex: You go to see the kumbh mela, there you will buy the ticket/token to enter into the festival which is called authentication and after that, with this token you can access resources of mela if you are allow to do so which is called authorisation
Basically in simple words, jwt is
token or ticket to enter into the festival or to log in to your system which is called authentication and access the resources if you are allow to do so which is called authorisation
3. Advantages of Node.js authentication with JWT
Node.js authentication with JWT has several advantages over the traditional authentication process, primarily the scalability of stateless applications. And since it’s becoming popular among such heavyweights as Facebook and Google, it’s adoption across the industry likely will continue to grow.
Other advantages include:
- Simple verification through a JSON Web Token
- You can use an authentication service or outsource it
- Provides more trustworthiness than cookies or sessions
4. Why to use JWT??
JWT is an excellent choice to be passed in HTML and HTTP environments due to its smaller footprint when compared to other types of tokens
JSON Web Tokens can be signed using a shared secret and also by using public/private key pairs
- It is easier to work with JWT as JSON parsers are standard in most programming languages
- JWT is also suitable for implementing authorization in large-scale web applications
5. How to implement JWT??
Step-1: install jwt
npm install jsonwebtoken
Step-2: require jwt
const jwt = require('jsonwebtoken');
Step-3: encode/hash/generate token using sign() method of jwt
means generate the unique token for each user
let jwtSecretKey = process.env.JWT_SECRET_KEY;
let data = {
time: Date(),
userId: 12,
}
const token = jwt.sign(data, jwtSecretKey);
Imp Note:
Here you will see the data, in this you can pass anything related to user but it should be unique
In sign() method, you have to pass the data and the secret key which is nothing but just your private key which is used later to docode the token. In this code process.env.JWT_SECRET_KEY is accessing secret key from .env file
In JWT, sign() method is used to generate the token which also hash the token so that it will remain safe and private
Step-4: decode/access the token using verify() method of jwt
means access the token of each user
In this step, we have two means to access the token...
A. take the token from headers
let tokenHeaderKey = process.env.TOKEN_HEADER_KEY;
const token = req.header(tokenHeaderKey);
B. take the token from body
const token = req.body.user_token;
After accessing the token, decode it using secret key and you will get the data which you passed earlier
const verified = jwt.verify(token, jwtSecretKey);
if(verified){
return res.send("Successfully Verified");
}else{
// Access Denied
return res.status(401).send(error);
}
Imp Note:
- In JWT, verify() method is used to decode the token and get the data of user
6. Two ways to take the user id:
- Pass the user id to api and access it using req.params.user_id
app.get("/give/data/of/particular/user/:user_id",(req,res)=>{
const userid= req.params.user_id;
// use this user id to fetch user data
})
- Take the user id from the token you passed to api in form of header or body:
app.get("/give/data/of/particular/user",(req,res)=>{
// let data = {
// time: Date(),
// userId: 12,
// }
// This is the data which you passed in token, take user id from it
const verified = jwt.verify(token, jwtSecretKey);
if(verified){
const userid= verified.userId;
// use this user id to fetch user data
}else{
// Access Denied
return res.status(401).send(error);
}
})
Thanks for reading this article...
If you like it, plz like and comment !!