首页 > 解决方案 > Microsoft for Xamarin Forms 的 active-directory-xamarin-native-v2 示例项目在 iOS 中不起作用

问题描述

我正在处理 office365 身份验证,从 github 获取代码,对于 android 构建它工作正常,但在 iOS 中没有从 office365 获取数据响应(令牌)。

项目链接 - https://github.com/Azure-Samples/active-directory-xamarin-native-v2

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

    async void OnSignInSignOut(object sender, EventArgs e)
    {
        AuthenticationResult authResult = null;
        IEnumerable<IAccount> accounts = await App.PCA.GetAccountsAsync();
        try
        {
            if (btnSignInSignOut.Text == "Sign in")
            {
                // let's see if we have a user in our belly already
                try
                {
                    IAccount firstAccount = accounts.FirstOrDefault();
                    authResult = await App.PCA.AcquireTokenSilent(App.Scopes, firstAccount)
                                          .ExecuteAsync();
                    await RefreshUserDataAsync(authResult.AccessToken).ConfigureAwait(false);
                    Device.BeginInvokeOnMainThread(() => { btnSignInSignOut.Text = "Sign out"; });
                }
                catch (MsalUiRequiredException ex)
                {
                    try
                    {

                        authResult = await App.PCA.AcquireTokenInteractive(App.Scopes)
                                                  .WithParentActivityOrWindow(App.ParentWindow)
                                                  .ExecuteAsync();

                        await RefreshUserDataAsync(authResult.AccessToken);
                        Device.BeginInvokeOnMainThread(() => { btnSignInSignOut.Text = "Sign out"; });
                    }
                    catch(Exception ex2)
                    {
                        slUser.IsVisible = true;
                    }
                }
            }
            else
            {
                while (accounts.Any())
                {
                    await App.PCA.RemoveAsync(accounts.FirstOrDefault());
                    accounts = await App.PCA.GetAccountsAsync();
                }

                slUser.IsVisible = false;
                Device.BeginInvokeOnMainThread(() => { btnSignInSignOut.Text = "Sign in"; });
            }
        }
        catch (Exception ex)
        {

        }
    }

    public async Task RefreshUserDataAsync(string token)
    {
        //get data from API
        slUser.IsVisible = true;
        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;

            Device.BeginInvokeOnMainThread(() =>
            {

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

                // just in case
                btnSignInSignOut.Text = "Sign out";
            });
        }
        else
        {
            await DisplayAlert("Something went wrong with the API call", responseString, "Dismiss");
        }
    }
}
}

我应该得到与 android build 相同的内容,但在 iOS 中没有从 office365 服务器获取令牌,似乎是证书问题,我发现下面的行需要遵循,以便在 iOS 中工作

此外,为了使令牌缓存工作并让 AcquireTokenSilentAsync 工作,必须遵循多个步骤:

1) 在您的 Entitlements.plist 文件中启用钥匙串访问,并在钥匙串组中指定您的捆绑标识符。

2) 在您的项目选项中,在 iOS Bundle Signing 视图中,为自定义权利字段选择您的 Entitlements.plist 文件。

3) 签署证书时,确保 XCode 使用相同的 Apple ID。

以上来自微软网站

下面是 Entitlements.plist 文件详细信息 - 我正在使用的钥匙串访问组 $(AppIdentifierPrefix)com.oauth.office365 其中 com.oauth.office365 是我的包标识符

标签: iosxamarin.forms

解决方案


推荐阅读