简体   繁体   English

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

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

I have just started to learn hapi.js .我刚刚开始学习hapi.js And I'm trying to understand the code of auth.我正在尝试了解身份验证的代码。 How this works.这是如何工作的。 For that, I followed hapi-auth-jwt2 .为此,我遵循hapi-auth-jwt2

After that when I call the API from the postman, I didn't get any output.之后,当我从邮递员那里调用 API 时,我没有得到任何输出。

This is my server.js file and I run node server.js .这是我的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);
});

From Postman来自邮递员

图像

You will need to create a token for each user ( people ) by using the (secret) key like:您需要使用(秘密)密钥为每个用户( 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);
})();

And here is the token for the given payload:这是给定有效负载的令牌:

$ node auth.js
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkplbiBKb25lcyIsImlhdCI6MTU3ODQ5MzQwOH0._kFvxkURRmzq4DgAEzAURca9yIv6KCf7MsolCiWsmRY

The token contains the payload, which is checked in validate , again, by using the same key (actually just id would be sufficient).令牌包含有效负载,再次使用相同的密钥在validate检查(实际上只需要id就足够了)。 Now access the restricted route using the token for the user { id: 1, name: 'Jen Jones' } :现在使用用户{ 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!"}

One of the key objectives of an authentication scheme (eg hapi-auth-jwt2 plugin/module) is to reject any requests to a given route as early as possible to avoid consuming resources on the server.身份验证方案(例如 hapi-auth-jwt2 插件/模块)的关键目标之一是尽早拒绝对给定路由的任何请求,以避免消耗服务器上的资源。 So any request that does not have a valid JWT will be rejected an never reach the validate function.因此,任何没有有效 JWT 的请求都将被拒绝,并且永远不会到达验证函数。

In order to see any sort of console.log you will need to send a well-formed http request with a JWT header, cookie or query parameter.为了查看任何类型的 console.log,您需要发送一个格式良好的 http 请求,其中包含 JWT 标头、cookie 或查询参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM