简体   繁体   English

如何使用Azure移动应用后端从Microsoft Graph中为经过身份验证的用户获取用户信息?

[英]How do I grab user info from Microsoft Graph for authenticated user using Azure mobile app backend?

Using the backend of my app, I am attempting to capture information from Microsoft Graph for a user that has been authenticated and then add that user to a database. 使用我的应用程序后端,我试图从Microsoft Graph捕获经过身份验证的用户的信息,然后将该用户添加到数据库中。 The authentication appears to be working correctly, but the user is never added to the database. 身份验证似乎可以正常工作,但是永远不会将用户添加到数据库中。 I am really stuck on this. 我真的很坚持。 I've studied the online documentation extensively, but have been unable to find a solution. 我已经广泛研究了在线文档,但是一直找不到解决方案。 If I could just tell if the user properties were getting populated, I could figure out what's going on, but I've been unable to do that since the code runs on the server. 如果我只能确定用户属性是否已填充,则可以弄清楚发生了什么,但是由于代码在服务器上运行,所以我一直无法做到这一点。 (I've attempted to remote debug, but have been unable to successfully set a breakpoint.) Can anyone tell me what I'm doing wrong in the code below? (我曾尝试进行远程调试,但无法成功设置断点。)有人可以告诉我我在以下代码中做错了什么吗?

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;
    }
}

As to why this is failing, it is difficult to determine without an actual error message. 至于失败的原因,如果没有实际的错误消息很难确定。 There are simply to many variables/potential failure points involved to say for sure. 可以肯定地说,涉及许多变量/潜在故障点。

That said, you can reduce the number of potential failure points by using the Microsoft Graph .NET Client Library . 就是说,您可以使用Microsoft Graph .NET Client Library减少潜在故障点的数量。 There is also a NuGet package available: Install-Package Microsoft.Graph . 还有一个可用的NuGet软件包Install-Package Microsoft.Graph

This library will handle composing the Microsoft Graph and deserializing the response into an object. 该库将处理组成Microsoft Graph并将响应反序列化为对象。 Along with removing a risk factor, it will greatly simplify your code: 除了消除风险因素,它还将大大简化您的代码:

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();

I would also suggest implementing a monitoring solution that can trap exceptions on the server. 我也建议您实施一种监视解决方案,以捕获服务器上的异常。 This will help with debugging. 这将有助于调试。 If you're running on Azure, I strongly recommend using Application Insights . 如果您在Azure上运行,强烈建议使用Application Insights Aside from being free to get started, it is effectively a "click once, get monitoring" solution. 除了可以自由上手之外,它实际上是一种“单击一次,开始监视”的解决方案。 It will handle wiring up the server and provide reporting for any exceptions it runs into. 它将处理服务器连接并提供有关运行中的任何异常的报告。

Note that you can also use App Insights with your own servers or apps hosted on other services (ie AWS, RackSpace), there may however be some manual configuration required. 请注意,您还可以将App Insights与您自己的服务器或托管在其他服务(例如AWS,RackSpace)上的应用程序一起使用,但是可能需要进行一些手动配置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何配置 Azure Function 以在不使用用户帐户的情况下调用 Microsoft Graph? - How do I configure an Azure Function to call the Microsoft Graph without using a user account? 我从 IdS4 对用户进行了身份验证,如何在我的 MVC 客户端中使用此信息? - I authenticated a user from IdS4, how do I use this info in my MVC client? 如何在Azure移动应用程序服务(.Net后端)中访问用户数据 - How to access user data in Azure Mobile App services (.Net backend) 通过浏览器表单进行身份验证时从Azure API应用获取用户信息 - Getting user info from Azure API App when authenticated via browser form 从.NET Backend Azure Mobile Service中的身份验证令牌获取名称,电子邮件ID等用户信息 - Get user info like name, email Id etc from authentication token in .NET Backend Azure Mobile Service 使用.Net后端Azure移动服务中的Microsoft帐户对用户进行身份验证,登录后出现错误 - Authenticate user using Microsoft Account in .Net backend Azure Mobile service giving error after login 如何使用 Microsoft Graph api 从 azure 活动目录中获取所有用户属性 - How to get all user attributes from azure active directory using Microsoft Graph api 如何在MVC应用程序中使用Microsoft Graph访问其他用户的资源(特别是电子邮件)? - How can I access another user's resources (specifically emails) using Microsoft Graph in an MVC app? 如何使用Microsoft Graph SDK向用户添加拥有的设备? - How do I add an owned device to a user using the Microsoft Graph SDK? C#控制台应用程序,用于使用Microsoft Graph在Azure Active Directory中创建用户 - C# Console App to Create User in Azure Active Directory using Microsoft Graph
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM