[英]How do I configure an Azure Function to call the Microsoft Graph without using a user account?
[英]How do I grab user info from Microsoft Graph for authenticated user using Azure mobile app backend?
使用我的應用程序后端,我試圖從Microsoft Graph捕獲經過身份驗證的用戶的信息,然后將該用戶添加到數據庫中。 身份驗證似乎可以正常工作,但是永遠不會將用戶添加到數據庫中。 我真的很堅持。 我已經廣泛研究了在線文檔,但是一直找不到解決方案。 如果我只能確定用戶屬性是否已填充,則可以弄清楚發生了什么,但是由於代碼在服務器上運行,所以我一直無法做到這一點。 (我曾嘗試進行遠程調試,但無法成功設置斷點。)有人可以告訴我我在以下代碼中做錯了什么嗎?
class MicrosoftAccountInfo
{
public string id { get; set; }
public string displayName { get; set; }
public string mail { get; set; }
}
[MobileAppController]
public class MicrosoftAccountController : ApiController
{
MicrosoftAccountCredentials credentials;
string msRequestUrl;
MyAppContext context;
EntityDomainManager<User> domainManager;
// GET api/<controller>
public async Task<User> Get()
{
if (credentials == null)
{
credentials = await this.User.GetAppServiceIdentityAsync<MicrosoftAccountCredentials>(this.Request);
}
msRequestUrl = "https://graph.microsoft.com/v1.0/me/?$select=id,displayName,mail";
var client = new System.Net.Http.HttpClient();
var headerValue = "Bearer" + credentials.AccessToken;
client.DefaultRequestHeaders.Add("Authorization", headerValue);
var resp = await client.GetAsync(msRequestUrl);
resp.EnsureSuccessStatusCode();
var msInfo = await resp.Content.ReadAsStringAsync();
MicrosoftAccountInfo info = JsonConvert.DeserializeObject<MicrosoftAccountInfo>(msInfo);
context = new MyAppContext();
domainManager = new EntityDomainManager<User>(context, Request);
var user = context.Users.FirstOrDefault(u => u.Email == info.mail);
if (user == null)
{
user = new DataObjects.User { Email = info.mail, UserName = info.displayName, ProviderId = info.id };
await domainManager.InsertAsync(user);
}
else if (string.IsNullOrEmpty(user.ProviderId))
{
user.UserName = info.displayName;
user.ProviderId = info.id;
await context.SaveChangesAsync();
}
return user;
}
}
至於失敗的原因,如果沒有實際的錯誤消息很難確定。 可以肯定地說,涉及許多變量/潛在故障點。
就是說,您可以使用Microsoft Graph .NET Client Library減少潛在故障點的數量。 還有一個可用的NuGet軟件包 : Install-Package Microsoft.Graph
。
該庫將處理組成Microsoft Graph並將響應反序列化為對象。 除了消除風險因素,它還將大大簡化您的代碼:
Microsoft.Graph.GraphServiceClient graphClient =
new Microsoft.Graph.GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", "{your-access-token}");
return Task.FromResult(0);
}));
Microsoft.Graph.User user = await graphClient.Me.Request().GetAsync();
我也建議您實施一種監視解決方案,以捕獲服務器上的異常。 這將有助於調試。 如果您在Azure上運行,強烈建議使用Application Insights 。 除了可以自由上手之外,它實際上是一種“單擊一次,開始監視”的解決方案。 它將處理服務器連接並提供有關運行中的任何異常的報告。
請注意,您還可以將App Insights與您自己的服務器或托管在其他服務(例如AWS,RackSpace)上的應用程序一起使用,但是可能需要進行一些手動配置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.