c# - 尝试在 Xamarin Forms 中使用 microsoft graph 获取用户信息

标签 c# azure xamarin.forms microsoft-graph-api azure-ad-b2c

我想从登录用户那里获取数据,所以我在互联网上搜索,发现我可以使用 Azure AD Graph 或 Microsoft Graph。所以我选择使用 Microsoft Graph 并找到了这个解决方案 https://github.com/Azure-Samples/active-directory-xamarin-native-v2然后我尝试使用我的 azure b2c 登录来实现,所以我更改了一些代码,这是我的一些代码。这是我的 App.C

using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using Xamarin.Forms;

namespace UsingGraphApi
{
    public partial class App : Application
    {

        public static PublicClientApplication AuthenticationClient { get; private set; }
      //  public static PublicClientApplication PCA = null;
        //public static string ClientID = "a7d8cef0-4145-49b2-a91d-95c54051fa3f";
      //  public static string[] Scopes = { "User.Read" };
       // public static string Username = string.Empty;

        //public static UIParent UiParent = null;


        public App()
        {
            InitializeComponent();
            AuthenticationClient = new PublicClientApplication(Constants.ApplicationID);

            MainPage = new NavigationPage(new MainPage());
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}

这是我的 Constant.Cs

namespace UsingGraphApi
{
    public static class Constants
    {
        public static string ApplicationID = "c2026789-5e43-4d25-acc9-e00768d4b0b4";
        //public static string[] Scopes = { ApplicationID };
        public static string[] Scopes = { "User.Read" };
        public static string SignUpSignInPolicy = "B2C_1_signin";
        public static string ResetPasswordPolicy = "b2c_1_reset";
        public static string Authority = "https://login.microsoftonline.com/kgvaluecard.onmicrosoft.com/";


    }
}

这是我的 MainPage.Cs

using Microsoft.Identity.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;

namespace UsingGraphApi
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        protected override async void OnAppearing()
        {
            // let's see if we have a user in our belly already
            try
            {
                var result = await App.AuthenticationClient.AcquireTokenSilentAsync(Constants.Scopes);
                RefreshUserData(result.Token);
                //btnSignInSignOut.Text = "Sign out";
                await DisplayAlert("OK", "OK", "OK");

            }
            catch
            {
                // doesn't matter, we go in interactive more
               // btnSignInSignOut.Text = "Sign in";
            }
        }


        async void OnSignInSignOut(object sender, EventArgs e)
        {
            try
            {

                    var result = await App.AuthenticationClient.AcquireTokenAsync(
                    Constants.Scopes,
                    string.Empty,
                    UiOptions.SelectAccount,
                    string.Empty,
                    null,
                    Constants.Authority,
                    Constants.SignUpSignInPolicy);

                    RefreshUserData(result.Token);
                    //btnSignInSignOut.Text = "Sign out";

            }
            catch (Exception )
            {
                //
            }
        }

        public async void RefreshUserData(string Token)
        {

            //get data from API
            HttpClient client = new HttpClient();
            HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");
            message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", Token);
            HttpResponseMessage response = await client.SendAsync(message);
            string responseString = await response.Content.ReadAsStringAsync();
            if (response.IsSuccessStatusCode)
            {
                JObject user = JObject.Parse(responseString);

                slUser.IsVisible = true;
                lblDisplayName.Text = user["displayName"].ToString();
                lblGivenName.Text = user["givenName"].ToString();
                lblId.Text = user["id"].ToString();
                lblSurname.Text = user["mail"].ToString();
                lblUserPrincipalName.Text = user["userPrincipalName"].ToString();

                // just in case
                btnSignInSignOut.Text = "Sign out";


            }
            else
            {
                //DisplayAlert("Something went wrong with the API call", responseString, "Dismiss");
            }
        }

    }
}

应用程序可以部署并运行良好,但问题是我没有获取用户信息,我的代码是否有任何我不应该更改的错误 顺便说一句,这是我的 MainPage.Xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:UsingGraphApi"
             x:Class="UsingGraphApi.MainPage">

    <ContentPage.Content>
        <StackLayout>
            <Label Text="MSAL Xamarin Forms Sample" VerticalOptions="Start" HorizontalTextAlignment="Center" HorizontalOptions="FillAndExpand" />
            <BoxView Color="Transparent" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />
            <StackLayout x:Name="slUser" IsVisible="True" Padding="5,10">
                <StackLayout Orientation="Horizontal">
                    <Label Text="DisplayName " FontAttributes="Bold" />
                    <Label x:Name="lblDisplayName" />
                </StackLayout>
                <StackLayout Orientation="Horizontal">
                    <Label Text="GivenName " FontAttributes="Bold" />
                    <Label x:Name="lblGivenName" />
                </StackLayout>
                <StackLayout Orientation="Horizontal">
                    <Label Text="Surname " FontAttributes="Bold" />
                    <Label x:Name="lblSurname" />
                </StackLayout>
                <StackLayout Orientation="Horizontal">
                    <Label Text="Id " FontAttributes="Bold" />
                    <Label x:Name="lblId" />
                </StackLayout>
                <StackLayout Orientation="Horizontal">
                    <Label Text="UserPrincipalName " FontAttributes="Bold" />
                    <Label x:Name="lblUserPrincipalName" />
                </StackLayout>
            </StackLayout>
            <BoxView Color="Transparent" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />
            <Button x:Name="btnSignInSignOut" Text="Sign in" Clicked="OnSignInSignOut" VerticalOptions="End" HorizontalOptions="FillAndExpand"/>
        </StackLayout>
    </ContentPage.Content>

</ContentPage>

最佳答案

此代码示例用于从 Application Registration Portal 注册的聚合应用程序.

根据上面的应用程序配置代码,您正在从 Azure AD B2C 集成应用程序注册。在此场景中,此代码示例不适合,因为 Azure AD B2C 不支持 b2c 应用程序的 Microsoft Graph。如果我们想要将 Microsoft Graph 或 Azure AD Graph 与 Azure AD b2c 一起使用,我们需要注册一个单独的应用程序(请参阅 Azure AD B2C: Use the Graph API )。

要从 Azure AD B2C 获取用户信息,您可以直接解码id_token,该 token 在您进行身份验证后返回。请参阅下面的链接,了解如何解码 token 以检索信息:

How to decode JWT Token?

关于c# - 尝试在 Xamarin Forms 中使用 microsoft graph 获取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46924826/

相关文章:

azure - Azure AD Graph API 和 Microsoft Graph API 之间有什么区别

c# - Xamarin Forms - 用于延迟加载的绑定(bind) ListView

xamarin - 在内容页 XAMARIN FORMS 中调用 onresumo() 方法

google-maps - xamarin.forms map 隐藏缩放按钮 (+-)

c# - 从加权列表中选择一个随机项目

c# - 使用 Razor 按表中的日期对模型元素进行分组

c# - Azure 创建数据磁盘并将文件复制到其中

c# - Kinect SDK 1.7 |更改 KinectCursor 图像和大小

c# - 使用 .NET 4.0 更改 Windows 墙纸?

Azure Synapse 加载 : Split large compress files to smaller compressed files