【问题标题】:Trying to get users info with microsoft graph in Xamarin Forms试图在 Xamarin Forms 中使用 microsoft graph 获取用户信息
【发布时间】:2018-04-06 02:17:00
【问题描述】:

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

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>

【问题讨论】:

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


    【解决方案1】:

    此代码示例用于从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,在您进行身份验证后返回该信息。有关解码令牌以检索信息的信息,请参阅以下链接:

    How to decode JWT Token?

    【讨论】:

    • 谢谢兄弟,但我现在的主要问题是如何将它实现到 xamarin 表单。如果只有一个完整的解决方案。但感谢您的回答,它真的很有帮助
    • 我认为您的代码没有问题。它没有显示个人资料信息,因为正如费所说,您的应用程序没有在正确的位置注册。一旦你有一个有效的应用程序 ID,它应该可以工作。
    猜你喜欢
    • 2021-01-10
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多