JWT无法在Node.JS中正常工作

问题描述 投票:0回答:1

我很难像JWT上的Node JS那样使事情正常进行。首先,我的目标是(登录后)访问我的API的privateRoute路由。

我一直在打:

 authHeader == null 

authenticateToken中间件函数内部,尽管我尝试了很多事情。

所以我无法通过让我进入的authenticateToken级别。作为一种在标头中引入所需内容并能够通过的解决方案,我曾考虑过要创建一种进入方式,但仍然无法正常工作。

这里是相关代码。

app.get('/privateRoute', authenticateToken, function(req, res) {
    // Useful work to do, after logging in.
    .......
});


function authenticateToken(req, res, next) {
  // Gather the jwt access token from the request header
  const authHeader = req.headers['authorization'],
  token = authHeader && authHeader.split(' ')[1]

  if (token == null) {
    console.log('authenticateToken-401')
    return res.sendStatus(401) // There isn't any token.
  }
  // It never reaches this point !!!

  jwt.verify(token, 'myBigSecret', (err, user) => {
    console.log(err)
    if (err) {
      console.log('authenticateToken-403')
      return res.sendStatus(403)
    }
    req.user = user
  })
}


app.get('/entryRoute', function(req, res) {
  res.set('authorization', 'Bearer ' + myJWT_Token);
  res.redirect('/privateRoute');
});

有人可以告诉我我需要更改代码以使我的(可能不太好)解决方案正常工作吗?还是告诉我更好的方法?

下面是来自浏览器的一些额外信息,以备不时之需。

在FireFox菜单中,工具,Web开发人员,Web控制台;网络标签。我可以看到以下内容:

对于响应头(/ entryRoute):

Authorization : Bearer eyiwhfehihinR…CuwfihvihiL_hfgSt_J8D
Connection :keep-alive
Content-Length : 56
Content-Type : text/html; charset=utf-8
Date : Mon, 13 Apr 2020 09:46:55 GMT
Location : /privateRoute
Server : Xoibuy
Vary : Accept
Via : 1.1 vegur
X-Powered-By : Express

对于请求头(/ privateRoute):

Accept : text/html,application/xhtml+xm…ml;q=0.9,image/webp,*/ *;q=0.8
Accept-Encoding : gzip, deflate, br
Accept-Language : en-US,en;q=0.5
Connection : keep-alive
Host : myapp.herokuapp.com
Upgrade-Insecure-Requests : 1
User-Agent : Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/75.0
javascript node.js jwt authorization middleware
1个回答
0
投票

我的声誉仍然很低,所以我无法发表评论。我认为您的代码没有错。我认为您以错误的方式执行Http请求,因为未将授权标头传递给请求。我不知道您在前端使用什么语言,但是我假设它是JavaScript。您可以这样操作。

const consumeApi() = async () => {
   const response = await fetch('https://example.domain/endpoint', {
      method: 'POST' // could be any other methods (GET, POST, PUT, PATCH, DELETE, etc)
      headers: {
         'Authorization': 'Token some_token_value'
      }
   });

   // Response status other than 200
   if (response.status !== 200) return alert('Something wrong happened.'); 

   // Response status 200
   // do someting ...
}

使用上面的代码,您应该能够将授权标头添加到Http请求中。希望对您有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.