Sign in with Azure AD B2C to Xamarin Android app

Viewed 1034

After a week of researching authentication principles that would work with Azure AD B2C using the Xamarin to target the Android platform (not Xamarin.Forms), I'm finally asking for a little advice.

I've got an activity with a 'Sign in' button and I would like to log in to Azure on the button's touch event. Ideally I'd want to receive a token after the login steps are completed.

Here is the code that I have so far:

public class MainActivity : Activity
{
    public TaskCompletionSource<bool> ActivityResult { get; set; }
    public const int LocationActivityResult = 110;
    private static string AadInstance = "https://login.microsoftonline.com/{0}.onmicrosoft.com/";

    private PublicClientApplication _publicClientApplication;
    private string _authority;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        //partie pour le sign in 

        EditText editTextEmail = FindViewById<EditText>(Resource.Id.editTextEmail);
        EditText editTextPassword = FindViewById<EditText>(Resource.Id.editTextPassword);
        Button signIn = FindViewById<Button>(Resource.Id.buttonSignIn);

        signIn.Click += async (sender, e) =>
        {

            ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
            NetworkInfo networkInfo = connectivityManager.ActiveNetworkInfo;
            if (networkInfo == null)
            {
                Toast.MakeText(this, "Aucune connexion internet", ToastLength.Short).Show();
                Intent intent = new Intent(this.ApplicationContext, typeof(NotInternetActivity));
                intent.SetFlags(ActivityFlags.NewTask);
                StartActivity(intent);
            }
            else
            {

                /////essai pour la connexion
                _authority = string.Format(AadInstance, _azureSettings.Tenant);
                _publicClientApplication = new PublicClientApplication(
                    _authority,
                    _azureSettings.ClientId

                );
                await AcquireTokenAsync();

                /////passe sur la nouvelle actvité

                Intent intent = new Intent(this.ApplicationContext, typeof(PlantsActivity));
                intent.SetFlags(ActivityFlags.NewTask);
                StartActivity(intent);

            }

        };

    }
    Authentication _azureSettings = new Authentication
    {
        ClientId = "ClientId",
        ForgotPasswordPolicy = "ForgotPasswordPolicy",
        SignInOrSignUpPolicy = "SignInOrSignUpPolicy",
        Tenant = "Tenant"

    };

    protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        if (requestCode.Equals(LocationActivityResult))
        {
            if (CrossGeolocator.Current.IsGeolocationEnabled)
                this.ActivityResult.TrySetResult(true);
            else
                this.ActivityResult.TrySetResult(false);
        }
        else
        {
            AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
        }
    }

    public class Authentication
    {
        public string Tenant { get; set; }
        public string ClientId { get; set; }
        public string SignInOrSignUpPolicy { get; set; }
        public string ForgotPasswordPolicy { get; set; }
    }

    public Task<AuthenticationResult> AcquireTokenSilentAsync()
    {
        string[] scopes = { _azureSettings.ClientId };
        var res = _publicClientApplication.AcquireTokenSilentAsync(scopes, "", _authority, _azureSettings.SignInOrSignUpPolicy, false);
        return _publicClientApplication.AcquireTokenSilentAsync(scopes, "", _authority, _azureSettings.SignInOrSignUpPolicy, false);
    }

    public async Task<AuthenticationResult> AcquireTokenAsync()
    {
        string[] scopes = { _azureSettings.ClientId };
        return await _publicClientApplication.AcquireTokenAsync(scopes, "", UiOptions.SelectAccount, string.Empty, null, _authority, _azureSettings.SignInOrSignUpPolicy);
    }
}

I have put everything in the same class for now, just to test the outcomes. Any example that you could give me or any documentation on Xamarin.Android that you could point me too would be very helpful.

Thanks in advance.

2 Answers
Related