<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: AMANn5153</title>
    <description>The latest articles on DEV Community by AMANn5153 (@amann5153).</description>
    <link>https://dev.to/amann5153</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1022214%2Fa6275749-8163-44a4-a867-02fe832369e9.jpg</url>
      <title>DEV Community: AMANn5153</title>
      <link>https://dev.to/amann5153</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/amann5153"/>
    <language>en</language>
    <item>
      <title>User Authentication with JWT tokens in node js</title>
      <dc:creator>AMANn5153</dc:creator>
      <pubDate>Sun, 09 Apr 2023 23:33:47 +0000</pubDate>
      <link>https://dev.to/amann5153/user-authentication-with-jwt-tokens-in-node-js-1952</link>
      <guid>https://dev.to/amann5153/user-authentication-with-jwt-tokens-in-node-js-1952</guid>
      <description>&lt;p&gt;User authentication is the most important part of developing a website. To prevent any malicious activity in user accounts, we must implement a strong authentication system. Today, we will explore user authentication using JSON web tokens.&lt;/p&gt;







&lt;h2&gt;
  
  
  Getting Started
&lt;/h2&gt;

&lt;p&gt;first, we need to set up our Node.js boilerplate using Express. Make sure you have installed the npm and node &lt;/p&gt;

&lt;p&gt;create a directory for your project. We are going to use &lt;strong&gt;server&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;go inside the newly created  directory and run&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;npm init&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This will initialize our project with a package.json file.&lt;/p&gt;

&lt;p&gt;Now we will need to install Express&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;npm install express&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;create a new file index.js.&lt;/p&gt;

&lt;p&gt;put following code in the file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const express = require('express')
const app = express()
require("./db/conn")

const PORT=8083

app.use(require("./route/router"))

app.listen(PORT, () =&amp;gt; console.log(`connected to port number ${PORT}`))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;now we will need another dependency "mongoose"&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;npm install mongoose&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  Database Connection
&lt;/h2&gt;

&lt;p&gt;first we are going to connect our database.&lt;/p&gt;

&lt;p&gt;create a new folder as db and create a file inside it as conn.js&lt;/p&gt;

&lt;p&gt;paste the following code inside the file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose=require("mongoose")

const DB=process.env.DATABASE;

mongoose.connect(DB)
.then(()=&amp;gt;{
console.log("connection successfull")
})
.catch((e)=&amp;gt;{console.log(e)})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code snippet, we are connecting our database to MongoDB Atlas by importing Mongoose. We access the database connection link from the config.env file using the process.env.DATABASE variable. The config.env file stores custom environment variables, which can be created using the dotenv library&lt;/p&gt;




&lt;h2&gt;
  
  
  Creating User Collection
&lt;/h2&gt;

&lt;p&gt;lets create collection in database with  mongoose schema &lt;/p&gt;

&lt;p&gt;first create new folder with name models.&lt;/p&gt;

&lt;p&gt;create a new file user.model.js inside the folder &lt;/p&gt;

&lt;p&gt;user.model.js will have our user data such as name, email,password.&lt;/p&gt;

&lt;p&gt;paste the following code in the user.model.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose=require("mongoose");

const user=new mongoose.Schema({
name:{
type:String
},
email:{
type:String
},
password:{
type:String
},
token:{
type:String
}
)

const User=new mongoose.model("User",user)

module.exports=User
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we are creating schema here for the collection. &lt;br&gt;
Mongoose Schema defines document's properties, default values, types of data, validators, etc. In contrast, a Mongoose model provides an interface for the database to create, query, update, delete records, and so on. &lt;/p&gt;

&lt;p&gt;mongoose model accepts two parameters&lt;br&gt;
mongoose.model(collection name,collection schema)&lt;/p&gt;


&lt;h2&gt;
  
  
  Installing JWT
&lt;/h2&gt;

&lt;p&gt;before moving ahead lets just install the JWT package&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;npm i jsonwebtoken&lt;/p&gt;
&lt;/blockquote&gt;


&lt;h2&gt;
  
  
  Creating Routes and Authentication for User
&lt;/h2&gt;

&lt;p&gt;After creating collection now lets create routes.&lt;/p&gt;

&lt;p&gt;create a new folder "routes" in this folder create router.js file&lt;/p&gt;

&lt;p&gt;paste the following code into the file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express=require("express")
const router=express.Router()
const mongoose=require("mongoose")
const User=require("../model/user.model.js")

router.post("/Login",async (req,res)=&amp;gt;{       //Login  API

  const {email,Password}=req.body;

  if(!email || !Password){
   return res.status(403).json({error:"empty Fields"})
  }

  try{
    const exist=await User.findOne({email})
    if(exist){
      if(exist.password==Password){
        const token= await exist.generateAuthToken();
        res.cookie("authcookie",token,{
          expires:new Date(Date.now()+36000000),
          httpOnly:false,
        }) 
        res.status(200).json({token:token})                                                                                        
      }
      else{
        return res.status(401).json({error:"invalid credentials"})
      }
    }
    else{
      return res.status(401).json({error:"invalid credentials"})
}}catch(e){
  console.log(e)
  res.status(500).json({error:"wont be able to login"})
}}
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;here we are checking if email and password are not empty  if empty  we are returning status code 403 "Empty fields"&lt;/p&gt;

&lt;p&gt;If the password and email fields are not empty, we check if the email exists in the collection. If it does, we compare the entered password with the stored password to determine if they match. If the passwords match, we call the generateAuthToken() method to generate an authentication token.&lt;/p&gt;

&lt;p&gt;now go to user.model.js and paste this code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;user.methods.generateAuthToken=async function(){
    try{
    const tokenGen= jwt.sign({_id:this._id},process.env.SECRET)//genertaes token
    this.tokens=this.tokens.splice(0,1,{token:tokenGen})
     await this.save();
     return tokenGen;
    }
     catch(e){
        console.log(e)
     }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;generateAuthToken function generates the token . &lt;/p&gt;

&lt;p&gt;jwt.sign() sign takes two parameter id and JWT_secret and returns signed token (it is recommended that JWT_secret must be stored in config.env file).&lt;/p&gt;




&lt;h2&gt;
  
  
  Creating Middleware
&lt;/h2&gt;

&lt;p&gt;create a new folder middleware inside the folder  create a new file authentication.js&lt;/p&gt;

&lt;p&gt;paste the following code :-&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const jwt=require("jsonwebtoken")
const User=require("../models/user.model.js")


const authenticate= async (req,res,next)=&amp;gt;{
    try{
    const token= req.cookies.authcookie || req.headers["x-access-token"];  // taking token

    const authnToken= jwt.verify(token,process.env.SECRET)//verfify token with secret key{token is made up of user unique id and secret key} return unique id

 const userInfo= await User.find({_id:authnToken._id},{"tokens.token":token})//finding document that matches the unique id and token 

    if(!userInfo){res.status(209).json({error:"user info is not available"})}
        req.token=token;
        req.userinfo=userInfo;
        req.userId=userInfo[0]._id;
        next();
    }
    catch(e){
        res.status(401).json({message:"Please loggin first"})
        console.log(e)
    }

}

module.exports=authenticate


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The jwt.verify function takes a token and a secret key (which is composed of the user's unique ID) as parameters. It returns the user's unique ID.&lt;/p&gt;

&lt;p&gt;Now let’s create the /somepage route and update router.js with the following code to test the middleware&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;router.get("/somepage",authetication,(req,res)=&amp;gt;{
console.log("working")
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Checking The API In POSTMAN
&lt;/h2&gt;

&lt;p&gt;paste the localhost:8003/login into the path &lt;/p&gt;

&lt;p&gt;pass email and Password in body as a JSON&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzmjogfxm8qknjg1uruot.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzmjogfxm8qknjg1uruot.JPG" alt="Image description" width="800" height="461"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;it gives token as response &lt;/p&gt;

&lt;p&gt;for now copy this token &lt;/p&gt;

&lt;p&gt;Change the route to /somepage and include the x-access-token key in the headers with the token value pasted as its value. Then, send the request&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxvnrtmrhl8px5fgfhps3.JPG" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxvnrtmrhl8px5fgfhps3.JPG" alt="Image description" width="800" height="461"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;token is verified by middleware.&lt;/p&gt;




&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this tutorial we learned about JWT, authentication, authorization and how to develop an API using JWT token for authentication in Node.js.&lt;/p&gt;

</description>
      <category>node</category>
      <category>express</category>
      <category>mongoose</category>
    </item>
  </channel>
</rss>
