5 c# azure azure-active-directory azure-devops
我想从给定的 URL 获取访问令牌:
https://login.microsoftonline.com/{AzureTenantId}/oauth2/v2.0/token
Run Code Online (Sandbox Code Playgroud)
我正在传递以下参数,如 Microsoft 文档中所述:
client_id, scope, client_secret, grant_type。
当我点击此 URL 时,我收到“400 Bad Request”响应。
当我从 Postman 尝试同样的操作时,它成功并为我提供了一个访问令牌:
但不是来自我的代码:
public async Task<string> GetAuthorizationToken(string clientId, string ServicePrincipalPassword, string AzureTenantId) {
var result = "";
var requestURL = "https://login.microsoftonline.com/{AzureTenantId}/oauth2/v2.0/token";
var _httpClient = new HttpClient();
var model = new {
client_id = clientId,
scope = "{clentID}/.default",
client_secret = ServicePrincipalPassword,
grant_type = "client_credentials"
};
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(model), System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(requestURL)) {
Content = httpContent
};
using (var response = await _httpClient.SendAsync(httpRequestMessage)) {
if (response.IsSuccessStatusCode) {
var responseStream = await response.Content.ReadAsStringAsync();
return result;
} else {
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
您的http请求格式不正确,请尝试:
var _httpClient = new HttpClient();
var content = new FormUrlEncodedContent(new Dictionary<string, string> {
{ "client_id", "ClientID" },
{ "client_secret", "YourSecret" },
{ "grant_type", "client_credentials" },
{ "scope", "https://graph.microsoft.com/.default" },
});
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(requestURL))
{
Content = content
};
using (var response = await _httpClient.SendAsync(httpRequestMessage))
{
if (response.IsSuccessStatusCode)
{
var responseStream = await response.Content.ReadAsStringAsync();
return result;
}
else
{
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
正如Nan Yu 的答案的补充,您可能需要考虑使用库来实现此目的,而不是尝试自己实现。
例如,使用适用于 .NET 的 Microsoft 身份验证库 (MSAL),您将获得如下访问令牌:
// Setup MSAL
var client = ConfidentialClientApplicationBuilder
.Create("{client-id}")
.WithAuthority("https://login.microsoftonline.com/{tenant-id}/v2.0")
.WithClientSecret(/* retrieve from secure storage, do *NOT* put the secret in your code! */)
.Build();
// Retrieve an access token
var scopes = new string[] { "https://graph.microsoft.com/.default" };
var authResult = await clientApplication.AcquireTokenForClient(scopes).ExecuteAsync();
// The access token is in $authResult.AccessToken
Run Code Online (Sandbox Code Playgroud)
一个重要的优点是,您无需担心跟踪令牌有效性即可知道何时需要获取新令牌。如果您需要获取新的令牌,您只需AcquireTokenForClient再次调用,它就会为您确定是否需要获取新的令牌,或者您是否可以使用已经缓存的令牌。
| 归档时间: |
|
| 查看次数: |
7886 次 |
| 最近记录: |