使用Nodejs对http请求进行IIS身份验证

时间:2017-06-09 14:55:25

标签: node.js rest postman

HTTP GET / POST请求有一个问题。 当我使用DHC / Postman时,将参数发送到URL +端点,完美地工作。返回200.

但是使用代码,就像我的示例一样,显示一个401错误。

我搜索过这个问题,问题出在auth,不确定,see ......也许是一样的。

有了这个解释,我认为需要设置授权。但问题是当我访问该网站时,auth是自动,请参阅:

enter image description here

我的代码:

var jsonObject = JSON.stringify({ "UserName": login});

// prepare the header
var postheaders = {
    'Content-Type' : 'application/json',
    'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
};

// the post options
var optionspost = {
        host: "xxxxxxxxxx.com",
  //      path: '/Home/endpoint', //send the data for the endpoit with Postma works fine
        method: 'POST',
        headers : postheaders
};

console.info('Options prepared:');
console.info(optionspost);
console.info('Do the POST call');

// do the POST call
var reqPost = http.request(optionspost, function(res) {
    console.log("statusCode: ", res.statusCode);
    // uncomment it for header details
//  console.log("headers: ", res.headers);

    res.on('data', function(d) {
        console.info('POST result:\n');
        process.stdout.write(d);
        console.info('\n\nPOST completed');
    });
});

// write the json data
reqPost.write(jsonObject);
reqPost.end();
reqPost.on('error', function(e) {
    console.error(e);
});

Obs。:这个网站来自我的公司(.NET)并与IIS集成(Active Directory登录用户进行身份验证),当我访问时,会自动记录...我真的不知道如何解决这个问题

Obs II。:我尝试使用一个匿名的新标签并在线使用DHC,我的帖子不起作用。这个应用程序只适用于网络公司和客户端(使用邮件与我的电脑)。

Obs III。:请求来自服务器,来自我服务器的登录具有访问该站点的所有权限,当我请求时,就像我是匿名的,但如果我对REST Client / Postman做同样的事情,工作得很好。我需要它与我的服务器的http请求一起使用。

2 个答案:

答案 0 :(得分:2)

您可以使用像ntlm-webapi这样的模块,它允许您使用NTLM身份验证。这样请求就会通过。只需确保您使用的用户已获得该服务器的授权。

var Request = require('ntlm-webapi');

var request = new Request({
    url: "http://some.restful.api.org/you/want/to/call",
    username: 'username',
    password: 'password',
    domain: 'company_domain'
});

request.get(function(err, result){

    if (err) console.log (err);

    console.log (result);
});

答案 1 :(得分:1)

您似乎忘了在代码中添加Authorization标题

// prepare the header
var postheaders = {
    'Authorization' : 'Negotiate '+ yourAccessKey,
    'Content-Type' : 'application/json',
    'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
};