hapi-auth-jwt2 作品在 hapi.js 应用程序中不起作用?

hapi-auth-jwt2 works is not working in hapi.js app?

刚开始学习hapi.js. And I'm trying to understand the code of auth. How this works. For that, I followed hapi-auth-jwt2

之后,当我从邮递员那里调用 API 时,我没有得到任何输出。

这是我的 server.js 文件,我 运行 node server.js

'use strict';

const Hapi = require('@hapi/hapi');
const jwt = require('jsonwebtoken');
const people = {
  1: {
       id: 1,
       name: 'Jen Jones'
  }
};

// bring your own validation function
const validate = async function (decoded, request, h) {
  // do your checks to see if the person is valid    
  if (!people[decoded.id]) {
      return { isValid: false };
  }
  else {
      return { isValid: true };
  }
};

const init = async () => {
  const server = Hapi.server({
      port: 3000,
      host: 'localhost'
  });
  await server.register(require('hapi-auth-jwt2'));
  server.auth.strategy('test', 'jwt',
      {
          key: 'GSFDSFJDSKGJD;GJRTWERIUEWFJDKL;GVCXVNMXCVCNVS;DLGFJKGFJDHGJFKHGJERHTKERHERJHTKREHJ', // Random String
          validate,
          verifyOptions: { algorithms: ['HS256'] }
    });
  server.auth.default('test');


  server.route([
    {
        method: 'GET',
        path: '/restricted',
        config: {
            auth: 'test'
        },
        handler: function (request, h) {
            console.log("request.headers.authorization ::: ", request.headers.authorization);
            const response = h.response({ text: 'You used a Token!' });
            response.header("Authorization", request.headers.authorization);
            return response;
        }
    }
  ]);


  await server.start();
  return server;
};

process.on('unhandledRejection', (err) => {

  console.log(err);
  process.exit(1);
});

init().then(server => {
  console.log('Server running at:', server.info.uri);
})
.catch(err => {
   console.log(err);
});

来自邮差

您需要使用(秘密)密钥为每个用户 (people) 创建一个令牌,例如:

const jwt = require('jsonwebtoken');

(async() => {
  const key = 'GSFDSFJDSKGJD;GJRTWERIUEWFJDKL;GVCXVNMXCVCNVS;DLGFJKGFJDHGJFKHGJERHTKERHERJHTKREHJ';
  const payload = { id: 1, name: 'Jen Jones' };
  const token = await jwt.sign(payload, key);
  console.log(token);
})();

这里是给定负载的令牌:

$ node auth.js
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkplbiBKb25lcyIsImlhdCI6MTU3ODQ5MzQwOH0._kFvxkURRmzq4DgAEzAURca9yIv6KCf7MsolCiWsmRY

令牌包含有效负载,再次使用相同的密钥在 validate 中检查(实际上只需 id 就足够了)。现在使用用户 { id: 1, name: 'Jen Jones' }:

的令牌访问受限路由
$ curl -v -H "Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkplbiBKb25lcyIsImlhdCI6MTU3ODQ5MzQwOH0._kFvxkURRmzq4DgAEzAURca9yIv6KCf7MsolCiWsmRY"   http://localhost:3000/restricted
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET /restricted HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.58.0
> Accept: */*
> Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkplbiBKb25lcyIsImlhdCI6MTU3ODQ5MzQwOH0._kFvxkURRmzq4DgAEzAURca9yIv6KCf7MsolCiWsmRY
> 
< HTTP/1.1 200 OK
< authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkplbiBKb25lcyIsImlhdCI6MTU3ODQ5MzQwOH0._kFvxkURRmzq4DgAEzAURca9yIv6KCf7MsolCiWsmRY
< content-type: application/json; charset=utf-8
< cache-control: no-cache
< content-length: 28
< accept-ranges: bytes
< Date: Wed, 08 Jan 2020 14:26:04 GMT
< Connection: keep-alive
< 
* Connection #0 to host localhost left intact
{"text":"You used a Token!"}

身份验证方案(例如 hapi-auth-jwt2 plugin/module)的主要目标之一是尽早拒绝对给定路由的任何请求,以避免消耗服务器上的资源。 因此,任何没有有效 JWT 的请求都将被拒绝,并且永远不会到达验证函数。

为了查看任何类型的 console.log,您需要发送带有 JWT header、cookie 或查询参数的 well-formed http 请求。