Answers for "nodejs jwt"

2

nodejs jwt

var jwt = require("jsonwebtoken");
const config = require("config"); // store jwt token seret in it.....
const { check, validationResult } = require("express-validator"); //validater fields 

module.exports = (req, res, next) => {
  //Get Token from header

  const token = req.header("x-auth-token");

  //Check if not token

  if (!token) {
    return res.status(401).json({ msg: "No token ,authorized" });
  }

  //Verify Token
  try {
    const decoded = jwt.verify(token, config.get("jwtToken"));
    req.user = decoded.user;
    console.log(req.user);
    next();
  } catch (error) {
    res.status(401).json({ msg: "Token is not valid" });
  }
};


//Controller------

module.exports.Login = async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }
    const { Email, Phone_No, Password } = req.body;
    try {
        //See if user exists
        let user = await User.findOne({Emai});

        if (!user) {
            res.status(400).json({ msg: "Invalid Credentials !" });
        }

        //Match password
        const isMatch = await bcrypt.compare(Password, user.Password);

        if (!isMatch) {
            res.status(400).json({ msg: "Invalid Password !" });
        }
        //Jwt Token
        const payload = {
            user: {
                id: user.id,
            },
        };
        jwt.sign(
            payload,
            config.get("jwtToken"), { expiresIn: 360000 },
            (err, token) => {
                if (err) throw err;
                res.json({ msg: "Login success", token });
            }
        );
    } catch (err) {
        console.error(err.message);
        res.status(500).send("server error");
    }
};

//reactjs side

import axios from "axios";
import JwtDecode from "jwt-decode";
const setAuthToken = () => {
  const token = window.localStorage.getItem("token");
  console.log("Token get", token);
  if (token) {
    // Apply authorization token to every request if logged in
    axios.defaults.headers.common["x-auth-token"] = token;
  } else {
    // Delete auth header
    delete axios.defaults.headers.common["x-auth-token"];
  }
};

export default setAuthToken;


export function getDetails (token){
  try{
   return   JwtDecode(token);
  }catch(e){
    console.error(e);
  }
}
Posted by: Guest on August-25-2021
8

json web token npm global

$ npm install jsonwebtoken
Posted by: Guest on May-15-2020
13

jwt in node js

// index.js 

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();

// generate token for another API to use in req.header
app.post('/login', (req, res) => {
    const user = {
        id: 1,
        username: 'abhishek',
        email: "[email protected]"
    }
    let token = jwt.sign({ user: user }, 'shhhhh');
    res.send(token);
})

// verifyToken is a function that is used for check in API that token exist or not
// it can be put in between n number of API to check that authoriZed user loggedin or not.
app.get('/api', verifyToken, (req, res) => {
    try {
        jwt.verify(req.token, 'shhhhh', (error, authData) => {
            if (error) {
                res.send("not logged in")
            }
            res.json({
                message: "post Created",
                authData
            })
        })
    } catch (error) {
        res.send(error)
    }
})

// This funtion is middleware. 
function verifyToken(req, res, next) {
    try {
        const bearerHeader = req.headers['authorization'];
        if (typeof bearerHeader !== 'undefined') {
            const bearerToken = bearerHeader.split(' ')[1];
            req.token = bearerToken;
            next();
        }
        else {
            res.send("Not logged-in")
        }
    }
    catch {
        res.send("something went wrong")
    }
}

app.listen(3000, () => {
    console.log("server is runing")
})
Posted by: Guest on February-18-2021
2

jwt implementation in node js

const jwt = require("jsonwebtoken")

const jwtKey = "my_secret_key"
const jwtExpirySeconds = 300

const users = {
	user1: "password1",
	user2: "password2",
}

const signIn = (req, res) => {
	// Get credentials from JSON body
	const { username, password } = req.body
	if (!username || !password || users[username] !== password) {
		// return 401 error is username or password doesn't exist, or if password does
		// not match the password in our records
		return res.status(401).end()
	}

	// Create a new token with the username in the payload
	// and which expires 300 seconds after issue
	const token = jwt.sign({ username }, jwtKey, {
		algorithm: "HS256",
		expiresIn: jwtExpirySeconds,
	})
	console.log("token:", token)

	// set the cookie as the token string, with a similar max age as the token
	// here, the max age is in milliseconds, so we multiply by 1000
	res.cookie("token", token, { maxAge: jwtExpirySeconds * 1000 })
	res.end()
}
Posted by: Guest on July-12-2020
0

express jwt

// JWT MIDDLEWARE
const jwt = require('jsonwebtoken')
const httpError = require('http-errors')

module.exports = (req, res, next) => {
  try {
    const tokenHeader = req.headers.authorization.split('Bearer ')[1]
    const decoded = jwt.verify(tokenHeader, process.env.ACCESS_TOKEN_SECRET)
    req.user = decoded
    next()
  } catch (err) {
    next(httpError(401))
  }
}

// ROUTE LOGIN
app.get('/protect', authJwt, (req, res) => {
  console.log(req.user)
  res.send('aim in proteced route')
})

app.post('/login', (req, res) => {
  const bodyPayload = {
    id: Date.now(),
    username: req.body.username
  }
  const token = signAccessToken(res, bodyPayload)
  return res.status(200).json(token)
})

app.post('/refresh-token', (req, res) => {
  const refreshToken = signRefreshToken(req)
  res.status(200).json(refreshToken)
  res.end()
})

// JWT HELPER
const jwt = require('jsonwebtoken')
const httpError = require('http-errors')

exports.signAccessToken = (res, payload) => {
  try {
    if (payload) {
      const accessToken = jwt.sign({ ...payload }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1m' })
      const refreshToken = jwt.sign({ ...payload }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '90d' })
      res.cookie('refreshToken', `${refreshToken}`, { expired: 86400 * 90 })
      return { accessToken, refreshToken }
    }
  } catch (err) {
    return httpError(500, err)
  }
}

exports.signRefreshToken = (req) => {
  try {
    const getToken = req.cookies.refreshToken
    if (getToken) {
      const { id, username } = jwt.verify(getToken, process.env.REFRESH_TOKEN_SECRET)
      const accesssToken = jwt.sign({ id, username }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1m' })
      return { accesssToken }
    }
  } catch (err) {
    return httpError(401, err)
  }
}
Posted by: Guest on November-05-2020
0

nodejs jwt

var jwt = require("jsonwebtoken");
const config = require("config"); // store jwt token seret in it.....
const { check, validationResult } = require("express-validator"); //validater fields 

module.exports = (req, res, next) => {
  //Get Token from header

  const token = req.header("x-auth-token");

  //Check if not token

  if (!token) {
    return res.status(401).json({ msg: "No token ,authorized" });
  }

  //Verify Token
  try {
    const decoded = jwt.verify(token, config.get("jwtToken"));
    req.user = decoded.user;
    console.log(req.user);
    next();
  } catch (error) {
    res.status(401).json({ msg: "Token is not valid" });
  }
};


//Controller------

module.exports.Login = async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }
    const { Email, Phone_No, Password } = req.body;
    try {
        //See if user exists
        let user = await User.findOne({Emai});

        if (!user) {
            res.status(400).json({ msg: "Invalid Credentials !" });
        }

        //Match password
        const isMatch = await bcrypt.compare(Password, user.Password);

        if (!isMatch) {
            res.status(400).json({ msg: "Invalid Password !" });
        }
        //Jwt Token
        const payload = {
            user: {
                id: user.id,
            },
        };
        jwt.sign(
            payload,
            config.get("jwtToken"), { expiresIn: 360000 },
            (err, token) => {
                if (err) throw err;
                res.json({ msg: "Login success", token });
            }
        );
    } catch (err) {
        console.error(err.message);
        res.status(500).send("server error");
    }
};
Posted by: Guest on August-25-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language