[英]Need to generate Azure AD bearer token using C# rest call
我想通過C#REST調用生成Azure AD承載令牌。 我想在API調用中編寫用戶注冊邏輯。 我正在使用它作為令牌端點:
https://login.windows.net/[tenant-id]/oauth2/token
我也跟着中所述相同的步驟此文章。
我正在使用的用戶憑據是“全局管理員”。
但是我仍然收到“未經授權”錯誤。 請在下面找到代碼段和響應正文-
碼
using (HttpClient client = new HttpClient())
{
var tokenEndpoint = @"https://login.windows.net/<tanent-name>/oauth2/token";
var accept = "application/json";
client.DefaultRequestHeaders.Add("Accept", accept);
string postBody = @"resource=https%3A%2F%2Fgraph.microsoft.com%2F
&client_id=<client-id>
&grant_type=password
&username=<admin-user-name>
&password=<admin-pass>
&scope=openid";
using (var response = await client.PostAsync(tokenEndpoint, new StringContent(postBody, Encoding.UTF8, "application/x-www-form-urlencoded")))
{
if (response.IsSuccessStatusCode)
{
var jsonresult = JObject.Parse(await response.Content.ReadAsStringAsync());
var token = (string)jsonresult["access_token"];
return token;
}
else
return null;
}
}
反應體
{ StatusCode: 401, ReasonPhrase: 'Unauthorized',
Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
x-ms-request-id: cabefe46-ff73-4659-80a2-2f4136200900
Cache-Control: no-store, no-cache
P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
Set-Cookie: esctx=AQABAAAAAADX8GCi6Js6SK82TsD2Pb7...
Set-Cookie: x-ms-gateway-slice=004; path=/; secure; HttpOnly
Set-Cookie: stsservicecookie=ests; path=/; secure; HttpOnly
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Thu, 24 May 2018 13:43:39 GMT
Content-Length: 457
Content-Type: application/json; charset=utf-8
Expires: -1
}}
PS-還請指出是否還有其他方法可以在不執行REST調用的情況下添加新用戶。 我不想在客戶端應用程序中進行用戶注冊。
正如湯姆(Tom)所述,您的問題應由用戶無權訪問您的應用程序引起。
由於您使用的是ROPC授權流程,因此請確保用戶是該客戶端/ AAD應用的所有者。
您可以將onwer添加到AAD應用程序中:
轉到Azure門戶> Azure Acitve目錄>應用程序注冊>應用程序>設置>所有者>添加所有者>選擇該用戶。
此外,如果用戶啟用了MFA,則此流程將無效。
讓我知道是否有幫助!
還請指出是否還有其他方法可以在不執行REST調用的情況下添加新用戶。 我不想在客戶端應用程序中進行用戶注冊。
如果要創建用戶,我們可以使用Microsoft.Graph來完成。
在此之前,我們需要注冊Azure AD應用程序 。 並添加Microsoft圖形權限。 有關更多詳細信息,請參考Create User API 。
我使用Directory.ReadWrite.All權限對其進行測試。 不要忘記授予權限。
演示代碼。
string graphResourceId = "https://graph.microsoft.com/";
string authority = "https://login.microsoftonline.com/{0}";
string tenantId = "tenant Id";
string clientId = "client Id";
string secret = "secret";
authority = String.Format(authority, tenantId);
AuthenticationContext authContext = new AuthenticationContext(authority);
var accessToken = authContext.AcquireTokenAsync(graphResourceId, new ClientCredential(clientId, secret)).Result.AccessToken;
var graphserviceClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
requestMessage =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
return Task.FromResult(0);
}));
var user = new User
{
UserPrincipalName = "tomaccount1@xxxxx.onmicrosoft.com",
AccountEnabled = true,
DisplayName = "tom1",
PasswordProfile = new PasswordProfile
{
ForceChangePasswordNextSignIn = true,
Password = "1234qweA!@#$%6"
},
MailNickname = "tomaccount1"
};
var addUserResult = graphserviceClient.Users.Request().AddAsync(user).Result;
測試結果:
從Azure AD檢查
Packages.config
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Graph" version="1.9.0" targetFramework="net471" />
<package id="Microsoft.Graph.Core" version="1.9.0" targetFramework="net471" />
<package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="3.19.4" targetFramework="net471" />
<package id="Newtonsoft.Json" version="11.0.2" targetFramework="net471" />
<package id="System.IO" version="4.3.0" targetFramework="net471" />
<package id="System.Net.Http" version="4.3.3" targetFramework="net471" />
<package id="System.Runtime" version="4.3.0" targetFramework="net471" />
<package id="System.Security.Cryptography.Algorithms" version="4.3.1" targetFramework="net471" />
<package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="net471" />
<package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="net471" />
<package id="System.Security.Cryptography.X509Certificates" version="4.3.2" targetFramework="net471" />
</packages>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.