Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the name of the current user from the Json Web Token?

I am trying to get the name and other info from the jwt and I can so far only get the Id of the user.

This is the routes folder for authentication

const config = require("config");
const jwt = require("jsonwebtoken");
const { User } = require("../models/user");
const mongoose = require("mongoose");
const express = require("express");
const Joi = require("joi");
const _ = require("lodash");
const bcrypt = require("bcrypt");
const router = express.Router();

router.post("/", async (req, res) => {
  const { error } = validate(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  let user = await User.findOne({ email: req.body.email });
  if (!user) return res.status(400).send("Invalide email or password.");

  //compare the passowrd in the body and the password entered when registeration
  const validePassword = await bcrypt.compare(req.body.password, user.password);
  if (!validePassword)
    return res.status(400).send("Invalide email or password.");

  const token = user.generateAuthToken();

  res.send(token);
});

function validate(req) {
  const schema = {
    email: Joi.string()
      .required()
      .min(5)
      .max(250)
      .email(),
    password: Joi.string()
      .required()
      .min(7)
      .max(1024)
  };

  return Joi.validate(req, schema);
}

module.exports = router;

this is the middleware folder

const jwt = require("jsonwebtoken");
const config = require("config");

module.exports = function(req, res, next) {
  const token = req.header("x-auth-token");
  if (!token) return res.status(401).send("Access denied. No token provided.");

  try {
    const decoded = jwt.verify(token, config.get("jwtPrivateKey"));
    req.user = decoded;
    next();
  } catch (ex) {
    res.status(400).send("Invalid token.");
  }
};

This is the function for getting the current user when they are logged in...

export function getCurrentUser() {
  try {
    const jwt = localStorage.getItem(tokenKey);
    return jwtDecode(jwt);
  } catch (ex) {
    return null;
  }
}

This is all I have in my profile component file where the ComponentDidMount is located...

import React, { Component } from "react";
import { Link } from "react-router-dom";
import NavBar from "./navBar";
import "../profile.css";
import { getCurrentUser } from "../services/authService";

class Profile extends Component {
  state = {};

   async componentDidMount() {
    const currentUser = await getCurrentUser();
    console.log(currentUser)
  }

When I log the the currentUser this is what I get...

{_id: "5d96a81f9a2f1a8bd485f76c", iat: 1570751361}
iat: 1570751361
_id: "5d96a81f9a2f1a8bd485f76c"

PLEASE HELP

like image 554
Sami Avatar asked Oct 17 '25 05:10

Sami


1 Answers

if you need username in payload,you need to add username when you sign the token.If you can't sign with username for some reason,write another service to return username from userId or whatever field exist in your jwt.

userSchema.methods.generateAuthToken = function() { 
const token = jwt.sign( { _id: this._id,
                          isAdmin: this.isAdmin,
                          _username:this.username }, 
 config.get("jwtPrivateKey") ); 
 return token; 
};

i have added new _username:this.username key value pair inside the jwt.sign function, _username is the key and this.username should be your actual username which is in the database.

like image 136
Rajith Thennakoon Avatar answered Oct 19 '25 21:10

Rajith Thennakoon