簡體   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