我有一个web应用程序,其中用户使用方法定义的in this sample登录。
现在我想为这个用户调用Microsoft Graph。我已经看过很多文档了,应该怎么做让我很困惑。这就是我尝试过的。我不确定如何获取此用户的访问令牌。
//not sure about this
var token = await GetAccessToken();
var client = new GraphServiceClient(
new DelegateAuthenticationProvider(
requestMessage =>
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);
return Task.FromResult(0);
}));
var result = await client
.Me
.Request()
.GetAsync();
根据this documentation,我需要使用保密客户端流,但我不确定是否需要使用授权码流或代理。由于方法I followed here的原因,我无法访问授权码。
ConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithCertificate(clientCertificate)
.Build();
有没有人可以指导我如何获取用户的访问令牌?我应该使用授权码流还是代表授权码流?
发布于 2020-02-12 10:57:08
如果您正在遵循上面列出的sample,那么您就在正确的轨道上。在本教程之后,它展示了如何代表登录用户调用Microsoft Graph /me端点。在本示例中,ASP.NET核心中间件和MSAL.Net的复杂性封装在本教程的Microsoft.Identity.Web
部分中。
您应该已经在Azure门户中注册了Web应用程序。现在你将调用Microsoft Graph,你将需要为Web应用程序注册证书或密钥。然后在API权限中,确保选择了Microsoft API选项卡,并为Microsoft Graph选择所需的API。
然后,继续跟踪tutorial以使MSAL能够挂钩到OpenID连接事件,并兑换由ASP.NET核心中间件获得的授权码。一旦收到令牌,MSAL会将其保存到令牌缓存中(也有相关教程)。
继续学习本教程,您将添加返回GraphServiceClient
的GraphServiceClientFactory.cs
。当它接收到Microsoft Graph的访问令牌时,它将向Graph发出请求,发送报头中的访问令牌。代码是here
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
string accessToken = await acquireAccessToken.Invoke();
// Append the access token to the request.
request.Headers.Authorization = new AuthenticationHeaderValue(
Infrastructure.Constants.BearerAuthorizationScheme,
accessToken);
}
还有更多的设置要做,但按照教程操作,您应该能够获取一个令牌,然后使用它来调用Microsoft Graph。
发布于 2020-02-12 10:50:25
注意:您需要使用Microsoft.Graph引用您的项目
首先,您需要一个函数来请求访问令牌
async Task<string> Post(string uri, Dictionary<string, string> parameters)
{
HttpResponseMessage response = null;
try
{
using (var httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) })
{
response = await httpClient.PostAsync(uri, new FormUrlEncodedContent(parameters));
if (!response.IsSuccessStatusCode)
throw new Exception("post request failed.");
var content = response.Content.ReadAsStringAsync().Result;
if (string.IsNullOrWhiteSpace(content))
throw new Exception("empty response received.");
return content;
}
}
catch (Exception e)
{
throw new Exception(error);
}
}
然后,您将需要一个模型来处理来自web请求的响应
public class TokenRequest
{
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("access_token")]
public string AccessToken { get; set; }
}
然后,您需要一个函数来从web请求中提取数据
TokenRequest GetAccessToken()
{
// request for access token.
var parameters = new Dictionary<string, string>();
parameters.Add("client_id", "YOUR CLIENT ID");
parameters.Add("client_secret", "YOUR CLIENT SECRET");
parameters.Add("scope", "https://graph.microsoft.com/.default");
parameters.Add("grant_type", "client_credentials");
var response = Post(
$"https://login.microsoftonline.com/{YOUR TENANT ID}/oauth2/v2.0/token",
parameters).Result;
return JsonConvert.DeserializeObject<TokenRequest>(response);
}
然后请求经过身份验证的图形api客户端
GraphServiceClient GetClient()
{
var tokenRequest = GetAccessToken();
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) => {
await Task.Run(() => {
requestMessage.Headers.Authorization = new AuthenticationHeaderValue(
tokenRequest.TokenType,
tokenRequest.AccessToken);
requestMessage.Headers.Add("Prefer", "outlook.timezone=\"" + TimeZoneInfo.Local.Id + "\"");
});
}));
return graphClient;
}
然后使用客户端,您现在可以执行查询
var graphClient = GetClient();
var user = await graphClient
.Users["SOME EMAIL ADDRESS HERE"]
.Request()
.GetAsync();
非常重要:您还必须确保您在active directory应用程序注册上拥有适当的api权限。如果没有它,您将只能从图形api获得请求被拒绝的响应。
希望这能有所帮助。
https://stackoverflow.com/questions/60179534
复制相似问题