我正在尝试通过使用用户凭证来检索访问令牌。
我正在使用AcquireTokenAsync方法来检索令牌,而我正在使用以资源,客户端ID和用户凭据作为参数的构造函数。
pl_id=MDR_PLZ
ln_id=01N
dt_concluded=20191106115958796600
tx_seq_nr=122586
ts_seq_nr=1078
us_id=c0507387
我期望返回访问令牌,但是获取令牌时出现异常。以下是我收到的错误消息。
public async Task<IHttpActionResult> GetToken()
{
AuthenticationResult authenticationResult = null;
try
{
string authority = "https://login.microsoftonline.com/tenant";
string resource ="2424-234-234234-234-23-32423";
string username = "yxyzzz";
string password = "password";
string clientId="2424-234-234234-234-23-32423";
var useridpassword = new UserPasswordCredential(username, password);
AuthenticationContext context = new AuthenticationContext(authority);
context.TokenCache.Clear();
authenticationResult = await context.AcquireTokenAsync(resource, clientId, useridpassword);
return authenticationResult.AccessToken;
}
catch (Exception ex)
{
throw ex;
}
}
答案 0 :(得分:1)
答案 1 :(得分:0)
这是我用来获取令牌的代码。这就是我想要检索访问令牌的方法。
string authority = "https://login.microsoftonline.com/tenant";
string resource ="2424-234-234234-234-23-32423";
string username = "yxyzzz";
string password = "password";
string clientId="2424-234-234234-234-23-32423";
string tokenEndpointUri = authority + "/oauth2/token";
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("client_id", authmodel.ClientId),
new KeyValuePair<string, string>("client_secret", authmodel.ClientSecret),
new KeyValuePair<string, string>("resource", resource)
}
);
using (var client = new HttpClient())
{
HttpResponseMessage res = null;
client.PostAsync(tokenEndpointUri, content).
ContinueWith(t =>
{
try
{
res = t.Result;
}
catch (Exception ex)
{
throw ex;
}
})
.Wait();
string json = await res.Content.ReadAsStringAsync();
}
我正在json变量中获取访问令牌以及其他详细信息。如果要获取令牌值,则可以将其反序列化为.net Object并获取该值。