hapi-auth-bearer-token 是否仅用于 API 身份验证?

Is hapi-auth-bearer-token for API authentication only?

我一直在阅读有关 hapi 的不记名令牌模块的文档,想知道它是否仅适用于 API 身份验证或也适用于通用 Web 应用程序身份验证。

文档中有一些内容不清楚。

1) 令牌来自哪里? IOW,什么机制创建令牌?

2) 用户首先通过什么方式登录?

谢谢

I've been reading the docs on the bearer token module for hapi and wondering if it is suitable for only API authentication or for general purpose web application authentication as well.

不记名身份验证用于授权 API 个请求。

1) From where does the token originate? IOW, what mechanism creates the token?

您需要自行生成并验证令牌。

要生成、存储和验证令牌,您可以使用 uuid and bcryptjs(将令牌发送给用户,并将散列令牌保存在数据库中以供以后验证)。

以下示例使用 TypeScript。

import uuid from 'uuid';
import bcrypt from 'bcryptjs';

export interface GeneratedToken {
  token: string;
  hashedToken: string;
}

const generateToken = async function(): Promise<GeneratedToken> {
  return new Promise<GeneratedToken>((resolve, reject) => {
    let token = uuid.v4().replace(/-/g, '');
    bcrypt.genSalt(10, function(error, salt) {
      if (error) {
        reject(error);
      } else {
        bcrypt.hash(token, salt, function(error, hashedToken) {
          if (error) {
            reject(error);
          } else {
            resolve({
              token: token,
              hashedToken: hashedToken
            });
          }
        });
      }
    });
  });
};

const validateToken = function(token: string, hashedToken: string): Promise<boolean> {
  return new Promise<boolean>((resolve, reject) => {
    bcrypt.compare(token, hashedToken, function(error, result) {
      if (error) {
        reject(error);
      } else {
        resolve(result);
      }
    });
  });
};

2) By what means does the user login in the first place?

您需要使用另一种身份验证方案,它可以像在数据库中存储散列密码一样简单,并将它们与发送到您的 API 路由的数据进行比较。用于令牌的相同哈希方案工作得很好。