如果您不想“每次都填写我的凭证”,则一种解决方法是使用Resource Owner Password Credentials Grant flow。此流程可以轻松获得令牌。在控制台应用程序中,您可以直接使用用户帐户和密码获取受保护的Web API的访问令牌。下面的代码是供你参考:
static void Main(string[] args)
{
test().Wait();
}
public static async Task test()
{
using (HttpClient client = new HttpClient())
{
var tokenEndpoint = @"https://login.windows.net/a703965c-e057-4bf6-bf74-1d7d82964996/oauth2/token";
var accept = "application/json";
client.DefaultRequestHeaders.Add("Accept", accept);
string postBody = @"resource=https%3A%2F%2Fgraph.microsoft.com%2F //here could be your own web api
&client_id=<client id>
&grant_type=password
&[email protected]
&password=<password>
&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"];
}
}
}
}
但问题是,流量将直接在代码中暴露的用户名和密码,它带来潜在的攻击的风险,以及我们会一直避免直接处理用户凭据。因此,请确保您只是使用此流程在安全环境中进行测试。有关更多详细信息,请参阅this article。
如果你走这条路线,请务必阅读Vittorio的博客文章,了解此流程的局限性:http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-用户-通usernamepassword / – dstrockis