0% found this document useful (0 votes)
102 views4 pages

JWT Avec Authentification User With Nodejs: On Commence Par Installer Le Module Jsonwebtoken

This document discusses implementing JWT authentication with NodeJS for a user model. It includes setting up a User schema in MongoDB with a password, generating an access token on login, and verifying the token in a middleware with JWT. The key steps are: 1. Creating a User model with a password 2. Generating an access token on login 3. Creating an auth middleware to verify the token on requests

Uploaded by

driss nadhem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views4 pages

JWT Avec Authentification User With Nodejs: On Commence Par Installer Le Module Jsonwebtoken

This document discusses implementing JWT authentication with NodeJS for a user model. It includes setting up a User schema in MongoDB with a password, generating an access token on login, and verifying the token in a middleware with JWT. The key steps are: 1. Creating a User model with a password 2. Generating an access token on login 3. Creating an auth middleware to verify the token on requests

Uploaded by

driss nadhem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

JWT avec authentification USER with NodeJS

On commence par installer le module jsonwebtoken

npm install jsonwebtoken

Créer le model de User dans le dossier models

models/user.js
import mongoose from "mongoose"
var userSchema = mongoose.Schema({
    nom:{
        type:String,
        required:"nom is required"
    } ,
   
    email:{
        type:String,
        required:"Email is required",
        unique:true
    } ,
    password:{
        type:String,
        required:"password is required"
    } ,
   
});
const User=mongoose.model('User',userSchema)
    export default User

Routes/user.route.js

import express from 'express';

import {  createUser,getuserBYEmail} from '../controllers/users.js';

const router = express.Router();

router.post('/', createUser);

// localhost:3001/api/users/login

router.post('/login', getuserBYEmail);

export default router;

1
Fichier Controllers/user.js

import User from '../models/user.js';


import  jwt  from "jsonwebtoken"

export const createUser = async (req, res) => {


        const newUser = new User(req.body)
      try {
         await newUser.save();
 
         res.status(201).json(newUser );
     } catch (error) {
         res.status(409).json({ message: error.message });
     }
 }

 const generateAccessToken=(user) =>{


    return jwt.sign({user}, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '30s' });

  }
 export const getuserBYEmail = async (req, res) => {
    try {
        const{email,password}=req.body;
        const user = await User.find({email,password});
       if(user==""){  res.status(401).send('utilisateur non existant');
        return} ;
        const accessToken = generateAccessToken(user);
       res.status(200).json({
        accessToken
      })
    } catch (error) {
        res.status(404).json({ message: error.message });
    }
}

 
9- Créer middlewares/auth.js le fichier qui vérifiera qu’on détient le jeton.

middlewares/auth.js

import  jwt  from "jsonwebtoken"

export const auth=async(req,res,next)=>{


const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
  if (!token) {
    return res.sendStatus(401);

2
  }
  jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
    if (err) {
      return res.sendStatus(401);
    }
    req.user = user;
    next();
  });
 }

Fichier .env

npm install dotenv

ACCESS_TOKEN_SECRET=azerty

Dans le fichier app.js, on ajoute la nouvelle route pour user

import userRouter from "./routes/user.route.js"

app.use('/api/users', userRouter);

dans le fichier article.route.js ; si on veut afficher la liste des articles mais avec JWT ont doit importer le
module auth

import express from 'express';


import {auth} from "../middleware/auth.js"
import { getArticles, getArticleByID, createArticle, updateArticle, deleteArticle }
from '../controllers/articles.js';

const router = express.Router();


/**
 * @route   GET /api/articles
 * @desc    Get All articles
 * @access  Public
 */
router.get('/',auth, getArticles);

3
Après 30 secondes, le token ne sera plus valable

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy