How to wait for 'AuthenticationContext.AcquireTokenAsync()' synchronouslly?

笑着哭i 提交于 2019-12-05 07:29:57

How to wait for 'AuthenticationContext.AcquireTokenAsync()' synchronouslly?

I suspect this issue is caused by calling the async method in the UI thread. Currently, my workaround is wrapping the call a new work thread.

    private void button1_Click(object sender, EventArgs e)
    {
        Authorize().Wait();
    }

    private Task Authorize()
    {
        return Task.Run(async () => {
            var authContext = new AuthenticationContext("https://login.microsoftonline.com/common");

            var authResult = await authContext.AcquireTokenAsync
            (new string[] { "https://outlook.office.com/mail.readwrite" },
             null,
             "{client_id}",
             new Uri("urn:ietf:wg:oauth:2.0:oob"),
             new PlatformParameters(PromptBehavior.Auto, null));
        });
    }

I fought this problem for 2 days on Xamarin.Android. It just never returns from the AquireTokenAsync method. The answer is almost comical. You need to add the following in your MainActivity.cs:

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
    }

Funny thing is, it actually says ContinuationHelper... smh.

How to wait for 'AuthenticationContext.AcquireTokenAsync()' synchronouslly?

AcquireTokenAsync() returns a "Task". You just have to wait for it using ".Wait()". In your main program you just have to do this:

Task<AuthenticationResult> res = authContext.AcquireTokenAsync(resourceUri, clientID, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Auto));
res.Wait();
Console.WriteLine(res.Result.AccessToken);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!