繁体   English   中英

使用Node通过Azure AD进行身份验证

[英]Authenticate with Azure AD with Node

我的Azure Active Directory环境中具有本机客户端应用程序设置。 我正在尝试编写一个实用程序目的的Node应用程序,以与Azure管理API进行交互。 我的挑战只是对我的应用程序进行身份验证。 目前,我有:

let azure = {
  clientId: '[only-for-my-eyes]',
  key: '[only-for-my-eyes]',
  tenantDomain: 'mydomain.onmicrosoft.com',
  tenantId: '[only-for-my-eyes]'
};

let authenticationRequest = {
  url: `https://login.microsoftonline.com/${azure.tenantDomain}/oauth2/v2.0/authorize`,
  headers: {
    'Content-Type':'application/x-www-form-urlencoded'
  },            
  formData: {
    response_type: 'code',
    response_mode: 'form_post',
    grant_type:'client_credentials',
    resource: 'https://management.azure.com',
    client_id: azure.clientId,
    client_secret: azure.key
  }
};

request.post(authenticationRequest, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body);
  } else {
    console.log(response.statusCode);
    console.log(response.statusMessage);
  }
});

当上述运行时,将执行200状态代码块。 但是,它只是打印出一堆HTML。 如果我查看正确,它看起来就像登录屏幕的HTML。 我正在尝试获取可以传递给管理API的访问令牌。

我想念什么?

我相信特定的端点旨在用于具有这些给定参数的GET,而不是POST。 我怀疑您看到的可能只是一般错误消息:

抱歉,我们无法登录。

我们收到了一个错误的请求。

您要做的是通过POST请求调用授权页面。 您无需在此处发送POST(或GET)请求,您必须将用户重定向到该授权URL。

另外,您必须具有重定向URI(我在您的azure对象中看不到它)。 此重定向URI是您的应用程序的回调。 对于我剩下的答案,可以说它存储在azure.redirectUri

let url = 'https://login.microsoftonline.com/${azure.tenantDomain}/oauth2/v2.0/authorize?response_type=code&response_mode=form_post&client_id={azureclient_id}&resource=https%3A%2F%2Fmanagement.azure.com&redirect_uri={azure.redirectUri}'
response.writeHead(302, {
    'Location': url
});
response.end();

用户将被重定向到授权页面,并且必须接受(或拒绝)您的应用程序请求。 然后,用户被重定向回您的Node.js应用程序( azure.redirectUri )。 由于您的response_modeform_post ,如果用户接受了您的应用程序请求,那么您将在主体参数中收到授权代码。

使用该代码,您的应用程序将能够通过调用令牌端点来获取访问令牌。

为什么不只使用ARMClient 所有令人讨厌的代币业务都得到了照顾。

https://www.npmjs.com/package/armclient

初始化:

// ES5

var ArmClient = require('armclient');

var client = ArmClient({ 
  subscriptionId: '111111-2222-3333333',
  auth: ArmClient.clientCredentials({
    tenantId: '444444-555555-666666666',
    clientId: '777777-888888-999999999',
    clientSecret: 'aaaabbbbbccccc' // or servicePrincipalPassword 
  })
});

获取订阅中的资源:

client.get('https://management.azure.com/subscriptions/111-222-333-444/resourceGroups/lab/providers/Microsoft.Automation/automationAccounts', { 'api-version': '2015-10-31' })
  .then((res) => {
    console.log(res.body);
    console.log(res.headers);
  })
  .catch((err) => {
    console.log(err);
  });

暂无
暂无

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

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