Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在Xamarin应用程序中MSAL登录成功后关闭.Auth/login/done_C#_Azure_Xamarin.forms_Msal - Fatal编程技术网

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

C# 在Xamarin应用程序中MSAL登录成功后关闭.Auth/login/done,c#,azure,xamarin.forms,msal,C#,Azure,Xamarin.forms,Msal,我已经在应用程序中使用azure设置了AD(MSAL)身份验证,但在关闭成功登录后出现的窗口时遇到问题。在嵌入式浏览器中显示的带有返回到我的API主页的链接的页面仅表示“您已成功登录”,下面的链接将返回到上一页并转到我的API主页 下面是我在App.xaml.cs中的代码 public partial class App : Application { public static IPublicClientApplication PCA = null; public stati

我已经在应用程序中使用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;
    }
}
public分部类登录页面:ContentPage
{
公共登录页()
{
初始化组件();
}
异步void OnSignIn(对象发送方,事件参数e)
{
AuthenticationResult authResult=null;
IEnumerable accounts=wait App.PCA.GetAccountsAsync();
var current=连接性.NetworkAccess;
bool connectionFound=false;
如果(当前==NetworkAccess.Internet)
{
connectionFound=true;
}
字符串APIData=“”;
if(connectionFound==true)
{
尝试
{
如果(SignInButton.Text==“登录”)
{
尝试
{
IAccount firstAccount=accounts.FirstOrDefault();
authResult=wait App.PCA.AcquireTokenSilent(App.Scopes,firstAccount)
.ExecuteAsync();
}
捕获(MsalUiRequiredException ex)
{
尝试
{
authResult=wait App.PCA.AcquireTokenInteractive(App.Scopes)
.WithParentActivityOrWindow(App.ParentWindow)
.ExecuteAsync();
}
捕获(异常ex2)
{
Wait DisplayAlert(“获取令牌交互失败。有关详细信息,请参阅异常消息:”,ex2。消息,“解除”);
}
}
if(authResult!=null)
{
var content=await GetHttpContentWithTokenAsync(authResult.AccessToken);
SignInButton.Text=“注销”;
}
}
其他的
{
while(accounts.Any())
{
等待App.PCA.RemoveAsync(accounts.FirstOrDefault());
accounts=wait App.PCA.GetAccountsAsync();
}
});
SignInButton.Text=“登录”;
}
}
捕获(例外情况除外)
{
等待DisplayAlert(“身份验证失败。有关详细信息,请参阅异常消息:”,例如消息“驳回”);
}
等待任务;
APIData=getAPIData();
}
其他的
{
等待DisplayAlert(“连接错误”、“检查internet连接并重试”、“重试”);
}
如果(APIData!=“ConnectionError”)
{
等待Navigation.PushAsync(新主页(APIData));
}
其他的
{
等待任务。延迟(500);
等待DisplayAlert(“API下载错误”、“连接到API时出错”、“重试”);
}
//主页=新主页(APIData);
}
公共异步任务GetHttpContentWithTokenAsync(字符串令牌)
{
尝试
{
//从API获取数据
HttpClient=新的HttpClient();
HttpRequestMessage=新的HttpRequestMessage(HttpMethod.Get)https://graph.microsoft.com/v1.0/me");
message.Headers.Authorization=new System.Net.Http.Headers.AuthenticationHeaderValue(“承载者”,令牌);
HttpResponseMessage response=等待客户端.SendAsync(消息);
string responseString=wait response.Content.ReadAsStringAsync();
回报率;
}
捕获(例外情况除外)
{
Wait DisplayAlert(“对图形的API调用失败:”,例如消息“disease”);
返回例如ToString();
}
}
私有字符串getAPIData()
{
字符串APIData=“”;
尝试
{
APIData=新的WebClient().DownloadString(“***/api/data”);
}
捕获(例外e)
{
Console.WriteLine(如ToString());
apidat=“ConnectionError”;
}
返回数据;
}
}
我知道这与登录无关,目前无法访问api数据。我真的只是希望关闭身份验证窗口,然后从那里开始工作


感谢

我设法解决了这个问题,在第二次调用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");
     }
}