在Xamarin应用程序中成功登录MSAL后关闭.Auth / login / done

问题描述 投票:0回答:1

我一直在使用我的应用程序使用azure设置AD(MSAL)身份验证,但是在成功登录后关闭出现的窗口时遇到了问题。嵌入式浏览器中出现的页面以及指向我的API主页的链接使用下面的链接“您已成功登录”,返回上一页并转到我的API主页。

下面是我在App.xaml.cs中的代码

public partial class App : Application
{
    public static IPublicClientApplication PCA = null;

    public static string ClientID = "********-****-****-****-**********";

    public static string[] Scopes = { "User.Read" };
    public static string Username = string.Empty;

    public static object ParentWindow { get; set; }

    public App()
    {
        InitializeComponent();
    }

    protected override async void OnStart()
    {
        PCA = PublicClientApplicationBuilder.Create(ClientID)
            //.WithRedirectUri($"msal{ClientID}://auth")
            .WithRedirectUri("https://kpiapp-api-dev.azurewebsites.net/.auth/login/aad/callback")
            .WithIosKeychainSecurityGroup("com.microsoft.adalcache")
            .WithAuthority(AzureCloudInstance.AzurePublic, "********-****-****-****-**********") //TenantID
            .Build();

        MainPage = new NavigationPage(new LoginPage());

    }

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

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

和我的Loginpage.xaml.cs:

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

    async void OnSignIn(object sender, EventArgs e)
    {
        AuthenticationResult authResult = null;
        IEnumerable<IAccount> accounts = await App.PCA.GetAccountsAsync();

        var current = Connectivity.NetworkAccess;
        bool connectionFound = false;

        if (current == NetworkAccess.Internet)
        {
            connectionFound = true;
        }

        string APIData = "";

        if(connectionFound == true)
        {

            try
            {
                if (SignInButton.Text == "Sign in")
                {
                    try
                    {
                        IAccount firstAccount = accounts.FirstOrDefault();
                        authResult = await App.PCA.AcquireTokenSilent(App.Scopes, firstAccount)
                                                .ExecuteAsync();

                    }
                    catch (MsalUiRequiredException ex)
                    {
                        try
                        {
                            authResult = await App.PCA.AcquireTokenInteractive(App.Scopes)
                                                        .WithParentActivityOrWindow(App.ParentWindow)
                                                        .ExecuteAsync();
                        }
                        catch (Exception ex2)
                        {
                            await DisplayAlert("Acquire token interactive failed. See exception message for details: ", ex2.Message, "Dismiss");
                        }
                    }

                    if (authResult != null)
                    {
                        var content = await GetHttpContentWithTokenAsync(authResult.AccessToken);

                        SignInButton.Text = "Sign out";
                    }
                }
                else
                {
                    while (accounts.Any())
                    {
                        await App.PCA.RemoveAsync(accounts.FirstOrDefault());
                        accounts = await App.PCA.GetAccountsAsync();
                    }
});
                    SignInButton.Text = "Sign in";

                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Authentication failed. See exception message for details: ", ex.Message, "Dismiss");
            }

            await Task.Yield();

            APIData = getAPIData();

        }
        else
        {
            await DisplayAlert("Connection Error", "Check your internet connection and try again", "Try again");
        }

        if (APIData != "ConnectionError")
        {
            await Navigation.PushAsync(new MainPage(APIData));
        }
        else
        {
            await Task.Delay(500);
            await DisplayAlert("API Download error", "Error connecting to API", "Try again");
        }
    //MainPage = new MainPage(APIData);
}

    public async Task<string> GetHttpContentWithTokenAsync(string token)
    {
        try
        {
            //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();
            return responseString;
        }
        catch (Exception ex)
        {
            await DisplayAlert("API call to graph failed: ", ex.Message, "Dismiss");
            return ex.ToString();
        }
    }

    private string getAPIData()
    {
        string APIData = "";

        try
        {
            APIData = new WebClient().DownloadString("****/api/data");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            APIData = "ConnectionError";
        }

        return APIData;
    }
}

我知道登录后不会执行任何操作,目前将无法访问api数据。我真的只是想关闭身份验证窗口,然后从那里开始工作。

谢谢

c# azure xamarin.forms msal
1个回答
0
投票
我设法通过向第二个authResult调用中添加.WithUseEmbeddedWebView(true)来解决此问题,因此它看起来像这样:

catch (MsalUiRequiredException ex) { try { authResult = await App.PCA.AcquireTokenInteractive(App.Scopes) .WithParentActivityOrWindow(App.ParentWindow) .WithUseEmbeddedWebView(true) .ExecuteAsync(); } catch (Exception ex2) { await DisplayAlert("Acquire token interactive failed. See exception message for details: ", ex2.Message, "Dismiss"); } }

© www.soinside.com 2019 - 2024. All rights reserved.