JWT 未按预期使用 Node.JS

JWT is not working as expected with Node.JS

我很难让 JWTNode JS 上正常工作。 我先说我的目标是(登录后)访问我的 API.

privateRoute 路由

我总是打一个:

 authHeader == null 

authenticateToken中间件函数里面,虽然我已经尝试了很多东西。

所以我无法通过 authenticateToken 让我进入的级别。 作为介绍 header 内部所需内容并能够通过的解决方案,我考虑过创建一种进入途径,但它仍然不起作用。

这里是相关代码。

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 控制台;网络选项卡。我可以看到以下内容:

对于响应 headers (/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

对于请求 headers (/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

我的声誉仍然很低,所以我无法 post 发表评论。我认为您的代码没有任何问题。我认为您以错误的方式执行 Http 请求,因为授权 header 未传递给请求。我不知道您在前端使用的是什么语言,但我假设它是 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 请求添加授权 header。希望这有帮助。

-- 编辑 您可以尝试创建一个新的 HTML 文件。假设 example.html 看起来像这样

// example.html
<!DOCTYPE html>
<html>
<script>
   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 ...
   }

   // call the function directly after loading the HTML page
   consumeApi().then();
</script>
</html>

然后尝试通过网络浏览器打开 example.html 文件,它应该会直接调用您的 api。这样,您应该能够使用授权 header 向您的 node.js 服务器发出请求。希望这有帮助