如何从Json Web令牌获取当前用户的名称?

时间:2019-10-11 00:14:55

标签: node.js reactjs jwt

我正在尝试从jwt获取名称和其他信息,到目前为止,我只能获取用户的ID。

这是用于身份验证的路由文件夹

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;

这是中间件文件夹

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.");
  }
};

此功能用于在当前用户登录时获取他们...

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

这就是我的ComponentDidMount所在的配置文件组件文件中的全部内容...

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)
  }

当我登录currentUser时,这就是我得到的...

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

请帮助

1 个答案:

答案 0 :(得分:1)

如果有效负载中需要用户名,则在对令牌进行签名时需要添加用户名。如果由于某种原因而无法使用用户名进行签名,请编写另一个服务以从userId或jwt中存在的任何字段返回用户名。 / p>

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

我在jwt.sign函数内添加了新的_username:this.username键值对,_username是键,this.username 应为您的实际用户名在数据库中。