簡體   English   中英

生成承載令牌客戶端C#

[英]Generate bearer token client side C#

我正在使用部署在蔚藍環境中的REST服務。 我想通過從單獨的(控制台)應用程序中調用各種AP​​I函數來運行一些集成測試。 但是REST api使用承載令牌身份驗證。 我完全是天藍色的身份認證,所以我什至不知道這是否應該。

我嘗試使用此處找到的示例但還沒有運氣。

無論如何,我有兩個應用程序。 一個是運行代碼的控制台應用程序,另一個是Rest服務,我需要使用其承載令牌來訪問API調用。 我將它們稱為ConsoleApp和RestService。

我運行的代碼如下:

HttpClient client = new HttpClient();
string tenantId = "<Azure tenant id>";
string tokenEndpoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/token";
string resourceUrl = "<RestService app id url>";
string clientId = "<azure id of the ConsoleApp>";
string userName = "derp@flerp.onmicrosoft.com";
string password = "somepassword";

string tokenEndpoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/token";
var body = $"resource={resourceUrl}&client_id={clientId}&grant_type=password&username={userName}&password={password}";
var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");

var result=await client.PostAsync(tokenEndpoint, stringContent).ContinueWith<string>((response) =>
{
    return response.Result.Content.ReadAsStringAsync().Result;
});

JObject jobject = JObject.Parse(結果);

我得到的Json訊息:

錯誤:invalid_grant,錯誤說明:AADSTS50105:登錄的用戶未分配給應用程序“ RestService azureid”的角色

這是什么意思?如何從中獲得承載令牌?

請首先檢查是否啟用了控制台應用程序User assignment required的“ User assignment required

在您的azure廣告刀片中,單擊Enterprise applications ,在All applications刀片中搜索您的應用All applications ,然后單擊Properties 在此處輸入圖片說明

如果啟用了該功能,並且您的帳戶未在應用程序中分配訪問角色,則將收到錯誤消息。 請嘗試在您的應用中分配訪問角色:

在您的天藍色廣告刀片中,單擊“ Enterprise applications ,在“ All applications刀片中搜索控制台應用All applications ,單擊“ Users and groups ,單擊“ Add User按鈕,選擇您的帳戶並分配角色(編輯用戶並確保select role不是“ None Selected ):

在此處輸入圖片說明

請讓我知道是否有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM