必须提供JWT-Delete方法将令牌返回为null而不是用户令牌

时间:2019-12-25 12:19:05

标签: node.js express jwt http-delete

标题有问题。我将向您展示NodeJS中的代码。请求是blogRouter.delete

controllers / blog.js(仅删除方法)

    const blogsRouter = require('express').Router()
    const jwt = require('jsonwebtoken');
    const Blog = require('../models/blog')
    const User = require('../models/user')

    blogsRouter.delete('/:id', async (request, response, next) => {

      const token = getTokenFrom(request)
      console.log('token: ',token)

      try {
        const decodedToken = jwt.verify(token, process.env.SECRET)

        if (!token || !decodedToken.id) {
          return response.status(401).json({ error: 'token missing or invalid' })
        }
        const userid = await User.findById(decodedToken.id)
        const blogs = await Blog.findById(request.params.id)

        if(blogs.user.toString() === userid.toString()) {
          await Blog.findByIdAndRemove(request.params.id)
          response.status(204).end()
        } else {
          response.status(404).end()
        }
      }catch(exception){next(exception)}  
    })

当我控制台日志令牌时,我通过辅助函数getTokenFrom获得空值

getTokenFrom

const getTokenFrom = request => {
  const authorization = request.get('authorization')
  if (authorization && authorization.toLowerCase().startsWith('bearer ')) {
    return authorization.substring(7)
  }
  return null
}

在请求后令牌中工作正常。我能够创建博客。但是当我用delete方法做同样的事情时,它不会显示令牌。它说。因此它正确地返回了我的getTokenFrom函数,但我希望能够以delete方法访问令牌,以便能够删除某些博客。

控制器/登录

const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const loginRouter = require('express').Router()
const User = require('../models/user')


loginRouter.post('/', async (request, response) => {
    const body = request.body

    const user = await User.findOne({username: body.username})
    const passwordCorrect = user == null ? 
    false : await bcrypt.compare(body.password, user.passwordHash)

    if(!(user && passwordCorrect)) {
        return response.status(401).json({
            error: "Invalid username or passowrd"
        })
    }

    const userForToken = {
        username: user.username,
        id: user._id,
    }

    const token = jwt.sign(userForToken, process.env.SECRET)

    response.status(200).send({token, username: user.username, name: user.name})
})

module.exports = loginRouter

https://prnt.sc/qfjgka->这是一张图片。我发送http.delete请求,并获得令牌null。必须提供JWT。我不知道这是我的错误。我尝试了很多事情,但是没有用。 我试图用token.request.jwt定义令牌,但后来​​我没有定义它。

我只需要通过blogRoute.delete方法以某种方式访问​​该令牌。

感谢前进

编辑:这是我的发布方法,当我在此处控制台登录令牌时,它会返回令牌的值,但是当我在删除方法中执行相同的操作时,它将无法正常工作

blogsRouter.post('/', async (request, response, next) => {

  const body = request.body
  console.log('body', body)
  const token = getTokenFrom(request)
  console.log('token: ', token)

  try {
    const decodedToken = jwt.verify(token, process.env.SECRET)
    if (!token || !decodedToken.id) {
      return response.status(401).json({ error: 'token missing or invalid' })
    }

  const user = await User.findById(decodedToken.id)


  const blog = new Blog({
    title: body.title,
    author: body.author,
    url: body.url,
    likes: body.likes,
    user: user._id
  })


    const savedBlog = await blog.save()
    user.blogs = user.blogs.concat(savedBlog._id)
    await user.save()
    response.json(savedBlog.toJSON())
  } catch(exception) {
    next(exception)
  }
})

1 个答案:

答案 0 :(得分:0)

在记录请求标头的屏幕快照中,似乎没有授权标头,因此您遇到了错误。如果您能够成功发送授权标头,则该问题将得到解决。

顺便说一句,在每个路由中检查令牌并对其进行验证不是一个好的解决方案。

您最好使用身份验证中间件进行令牌验证。

1-)创建一个这样的身份验证中间件:

middleware \ auth.js

const jwt = require("jsonwebtoken");

module.exports = function(req, res, next) {

  let token;
  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith('Bearer')
  ) {
    token = req.headers.authorization.split(' ')[1];
  } 

  if (!token) {
     return res.status(401).json({ error: 'token missing' })
  }

  try {
    const decoded = jwt.verify(token, process.env.SECRET);
    req.user = decoded;
    next();
  } catch (ex) {
    return res.status(400).json({ error: 'token invalid' })
  }
};

2-)在需要身份验证的任何地方使用此身份验证中间件。现在我们的路线更短了。

const blogsRouter = require("express").Router();
const jwt = require("jsonwebtoken");
const Blog = require("../models/blog");
const User = require("../models/user");
const auth = require("../middleware/auth");

blogsRouter.delete("/:id", auth, async (request, response, next) => {
  try {

    const userid = request.user.id;    //we set the user in the auth middleware, so we can access it like this
    const blogs = await Blog.findById(request.params.id);

    if (blogs.user.toString() === userid.toString()) {
      await Blog.findByIdAndRemove(request.params.id);
      response.status(204).end();
    } else {
      response.status(404).end();
    }
  } catch (exception) {
    next(exception);
  }
});

blogsRouter.post("/", auth, async (request, response, next) => {
  try {
    const body = request.body
    const user = await User.findById(request.user.id);

    const blog = new Blog({
      title: body.title,
      author: body.author,
      url: body.url,
      likes: body.likes,
      user: user._id
    });

    const savedBlog = await blog.save();
    user.blogs = user.blogs.concat(savedBlog._id);
    await user.save();
    response.json(savedBlog.toJSON());
  } catch (exception) {
    next(exception);
  }
});

通过这种方式,您可以将令牌发送到授权标头中,格式为Bearer TOKEN.....