获取Microsoft Graph API的令牌。这是第一次允许身份验证用户(微软)并获取调用令牌服务的代码。正确发送请求。但不是获取状态代码302,以便可以将其重定向到登录页面。我收到状态代码200。
public async Task<string> GetBToken()
{
string url = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?"; //https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.UseDefaultCredentials = true;
clientHandler.AllowAutoRedirect = true;
using(var client = new HttpClient(clientHandler))
{
client.BaseAddress = new Uri(url);
// We want the response to be JSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
url = url + "grant_type=authorization_code&client_id=" + appId + "resource=https://graph.microsoft.com/ &response_mode=form_post&response_type=code&redirect_uri=http://localhost/5341/Home/AddC &state=12345&scope=" + string.Join(" ", scopes1);
var request = new HttpRequestMessage(HttpMethod.Get, url);
var result1 = client.SendAsync(request).Result;
result1.EnsureSuccessStatusCode();
string jsonString = await result1.Content.ReadAsStringAsync(); // await response.Content.ReadAsStringAsync();
return jsonString;
}
}
答案 0 :(得分:1)
您无法在幕后执行OAUTH流程,您需要直接将用户发送到https://login.microsoftonline.com/common/oauth2/v2.0/authorize?...
(即在浏览器中打开该URL)。
这个过程应该是:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?...
redirect_url
。此回调将包含您在#3中使用的授权码的查询参数。POST
发出https://login.microsoftonline.com/common/oauth2/v2.0/token?...
。这将返回您在调用Microsoft Graph API时使用的访问令牌。