Wednesday, May 25, 2022

Using WebAuthenticator with .NET Maui

 First create an authorization callback activity inside the Android assets folder: 

namespace MauiApp6.Platforms.Android
{
    [Activity(NoHistory = true, LaunchMode = LaunchMode.SingleTop, Exported = true)]
    [IntentFilter(new[] { Intent.ActionView },
                  Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
                  DataScheme = "ultranomadic")]
    internal class AuthCallbackActivity : WebAuthenticatorCallbackActivity
    {

        public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
        {
            base.OnCreate(savedInstanceState, persistentState);
        }
    }
}

Modify the AndroidManifest.xml file to include this query node inside the manifest node. 

<queries>
<intent>
<action android:name="android.support.customtabs.action.CustomTabsService" />
</intent>
</queries>

Finally, use the web authenticator to login.  

            WebAuthenticatorResult authResult = await WebAuthenticator.Default.AuthenticateAsync(
                new Uri("https://planner.ultranomadic.com/auth?returnUrl=ultranomadic://planner.ultranomadic.com"),
                new Uri("ultranomadic://"));

            string accessToken = authResult?.AccessToken;

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var json = client.GetStringAsync("https://planner.ultranomadic.com/api/testauthget").Result;