1

我刚刚开始学习hapi.js。我正在尝试理解身份验证的代码。这是如何工作的。为此,我关注了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);
});

从邮递员

图像

4

2 回答 2

1

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

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!"}
于 2020-01-08T14:28:03.187 回答
0

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

为了查看任何类型的 console.log,您需要发送带有 JWT 标头、cookie 或查询参数的格式良好的 http 请求。

于 2020-05-20T14:39:48.363 回答