代码之家  ›  专栏  ›  技术社区  ›  yusha uzumo

如何在node.js中使用需要用户名/密码身份验证的rest api

  •  2
  • yusha uzumo  · 技术社区  · 6 年前

    我想使用一个rest api,它需要node.js中的用户名/密码身份验证。使用api的代码如下:

    var request = require('request');
    
    var url = 'http://localhost:3000/api/v1/login/'
    
    request.get(url,{'auth': {'user': 'test35','pass': 'mypassword','sendImmediately': false}},function(err, httpResponse, body) {
      if (err) {
        return console.error('post failed:', err);
      }
    
      console.log('Post successful!  Server responded with:', body);
    });
    

    使用上面的代码,我得到的错误是:

    {
      "status": "error",
      "message": "API endpoint does not exist"
    }
    

    这个api是用meteor restivus编写的,您可以在下面的问题中看到它 answer here

    在api中,当我删除api的authRequired:true时,即删除

    {
            routeOptions: {
                authRequired: true
            }
      }
    

    在使用api的代码中 在上面 ,更改URL

    ' http://localhost:3000/api/v1/login/

    致:

    http://localhost:3000/api/v1/articles/

    运行“node accessrestapi.js”,我就可以使用rest api了!我不能正确地做的是当“authRequired:true”按上述设置时的身份验证!请帮忙

    1 回复  |  直到 5 年前
        1
  •  1
  •   coagmano    6 年前

    编辑:根据评论中的信息更新

    在登录以获取令牌和随后的请求之间,请求的样式有很大不同:

    用于登录

    这个 docs 指定登录操作必须使用 POST 请求到 /api/login/ 尸体上有 username email password 作为URL编码的参数

    var request = require('request');
    
    var url = 'http://localhost:3000/api/v1/login/'
    var user = 'test35';
    var pass = 'mypassword';
    
    // Save these for future requests
    var userId;
    var authToken;
    
    // Use POST instead of GET
    request.post(
      {
        uri: url,
        // I'm using form because it matches the urlEncoding behaviour expected by `restivus`
        form: { username: user, password: pass }
      },
      function(err, httpResponse, body) {
        if (err) {
          return console.error('post failed:', err);
        }
        var json = JSON.parse(body);
        authToken = json.data.authToken;
        userId = json.data.userId;
        console.log('Post successful!  Server responded with:', body);
      }
    );
    

    以后的请求

    现在,您需要使用先前保存的 userId authToken

    According to the docs ,也就是说 X-User-Id X-Auth-Token 所有后续请求的标题

    var request = require('request');
    
    var url = 'http://localhost:3000/api/v1/articles/'
    
    request.get({
      uri: url, 
      headers: {
        'X-User-Id': userId,
        'X-Auth-Token': authToken
      }
    }, function(err, httpResponse, body) {
      if (err) {
        return console.error('post failed:', err);
      }
    
      console.log('Get successful!  Server responded with:', body);
    });
    

    总而言之:

    我们要确保 身份验证令牌 在提出任何进一步要求之前。

    这意味着在第一个函数的回调中发出第二个请求,如下所示:

    var request = require('request');
    
    var url = 'http://localhost:3000/api/v1/login/';
    var user = 'test35';
    var pass = 'mypassword';
    
    // Save these for future requests
    var userId;
    var authToken;
    
    // Use POST instead of GET
    request.post(
      {
        uri: url,
        // I'm using form because it matches the urlEncoding behaviour expected by `restivus`
        form: { username: user, password: pass }
      },
      function(err, httpResponse, body) {
        if (err) {
          return console.error('post failed:', err);
        }
        var json = JSON.parse(body);
        authToken = json.data.authToken;
        userId = json.data.userId;
        console.log('Post successful!  Server responded with:', body);
    
        // And now we make the second request
        // Welcome to callback hell
        var articlesUrl = 'http://localhost:3000/api/v1/articles/';
    
        request.get({
          uri: articlesUrl, 
          headers: {
            'X-User-Id': userId,
            'X-Auth-Token': authToken
          }
        }, function(err, httpResponse, body) {
          if (err) {
            return console.error('post failed:', err);
          }
    
          console.log('Get successful!  Server responded with:', body);
        });
      }
    );