How can I get the name of the current user from the Json Web Token?
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.
Sami
Updated on June 07, 2022Comments
-
Sami almost 2 years
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
-
Sami over 4 yearshow to I do that I am faily new to coding
-
Rajith Thennakoon over 4 yearsplease find the code section where you create the jwt token from the server side.in there you can pass username as a input data to sign the jwt.what is your server side framework and language?
-
Sami over 4 yearsI'm using node and I will add the code where I create the JTW token in the top inside my post
-
Rajith Thennakoon over 4 years@Sami please post
user.generateAuthToken()
function,this is where generate the token -
Sami over 4 yearsuserSchema.methods.generateAuthToken = function() { const token = jwt.sign( { _id: this._id, isAdmin: this.isAdmin }, config.get("jwtPrivateKey") ); return token; };
-
Rajith Thennakoon over 4 years@Sami i have changed the answer,please check it