Auth0 + JWT + NodeJS + Express 最终用户身份验证(登录)

Auth0 + JWT + NodeJS + Express End-user authentication (Login)

为了管理我的客户对我的应用程序仪表板的访问,我切换到 Auth0 已经将近一年了。现在我需要实现对 RESTFULL API.

的访问

如果我按照说明使用 JWT 保护 NodeJS 应用程序,它会非常有效。问题是我不能正确确定最终用户的实现以获得访问此 API.

所需的令牌

我想在仪表板上创建 令牌 ,或者只是为 login/authentication 使用服务器端实现。我最后一次使用了对我自己的数据库的访问权限,并且工作出色。 我的问题是我不完全确定如何为最终用户使用 Auth0

有人实现了 RESTfull API 之前使用 Auth0 登录以获得 JWT 令牌吗?很高兴听到你的想法。

解决方案是使用不同的方法。

有一个 Auth0 端点使用用户的用户名和密码来登录服务。这样我可以获得经过身份验证的用户的 ID 和一个 JWT 令牌,我可以使用它来验证未来的请求。

https://auth0.com/docs/api/authentication#resource-owner-password

This flow should only be used from highly trusted applications that cannot do redirects. If you can use redirect-based flows from your apps we recommend using the Authorization Code Grant instead.

router.post('/login', function (req, res, next) {
  var options = {
    method: 'POST',
    url: process.env.AUTH0_URL_OAUTH,
    headers: {
      'Cache-Control': 'no-cache',
      'Content-Type': 'application/json'
    },
    body: {
      grant_type: 'password',
      username: req.body.username,
      password: req.body.password,
      audience: process.env.AUTH0_AUDIENCE,
      scope: process.env.AUTH0_SCOPE,
      client_id: process.env.AUTH0_CLIENT_ID,
      client_secret: process.env.AUTH0_CLIENT_SECRET
    },
    json: true
  };

  request(options, function (error, response, body) {
    if (error) {
      res.sendStatus(500); //We could not connect to the service
    } else {
      if (body.error) {
        console.log(body);
        res.status(400);
        res.send({
          error: body.error_description // There was an error with the user or password
        });
      } else {
        console.log(body);
        /**
         * Everything went well. We return the JWT
         */
        res.send({
          access_token: body.access_token,
          expires_in: body.expires_in,
          token_type: body.token_type
        });
      }
    };