使用Azure AD B2C登录到Xamarin Android应用 [英] Sign in with Azure AD B2C to Xamarin Android app

查看:79
本文介绍了使用Azure AD B2C登录到Xamarin Android应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在研究了将使用Xamarin定位到Android平台(而不是Xamarin.Forms)的Azure AD B2C可以使用的身份验证原理之后,我终于在征求一点建议.

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.

我有一个带有登录"按钮的活动,我想通过该按钮的touch事件登录到Azure.理想情况下,我想在登录步骤完成后收到令牌.

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.

以下是我到目前为止的代码:

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);
    }
}

我现在将所有内容放在同一个班上,只是为了测试结果.您可能会给我的任何示例或Xamarin.Android上的任何文档(也可能会指向我)都将非常有帮助.

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.

谢谢.

推荐答案

因此,在花了几周的时间之后,我终于能够做到这一点.

So after spending weeks on this I finally was able to do it.

所以我的应用程序现在具有Azure AD B2C后端,并且我可以从Xamarin Android(本机)应用程序进行身份验证并从Easy Tables访问数据.

So my app now has an Azure AD B2C backend, and I can authenticate from Xamarin Android (native) app and access data from my Easy Tables.

这是它的工作方式:

您首先需要从Azure B2C获得令牌,因此一旦成功,则authResult将保存新用户,您可以在其中访问令牌和用户名.

First thing you need is to get the token from Azure B2C, so once it is successfull, then authResult will hold the new user where you can access token and username.

PublicClientApplication publicClientApplication = new PublicClientApplication(AuthParameters.Authority, AuthParameters.ClientId);
var authResult = await publicClientApplication.AcquireTokenSilentAsync(AuthParameters.Scopes, "", AuthParameters.Authority, AuthParameters.Policy, false);
//      await Navigation.PushAsync(new SecurePage());
var result = authResult.Token;

            textbox.Text = authResult.User.Name;

第二件事是通过loginasync将令牌发送到您的mobileserviceclient.

Second thing is to send the token to your mobileserviceclient through loginasync..

JObject payload = new JObject();
payload["access_token"] = authResult.Token;
try
{
    var user = await MobileService.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, payload);
}

这是AuthParameters类,用于存储所需的数据:

This is the class AuthParameters which stores the data needed:

public class AuthParameters
{
    public const string Authority = "https://login.microsoftonline.com/YOURSITE.onmicrosoft.com/";
    public const string ClientId = "Client ID from B2C APP";
    public static readonly string[] Scopes = { ClientId };
    public const string Policy = "POLICY_NAME_FROM_B2CTenant";
}

现在在azure门户上,您应该拥有一个活动的Azure B2C应用程序和一个移动服务客户端.它们应该链接在一起,链接的方式就是通过此链接

Now on azure portal you should have an active Azure B2C App, and a mobile service client. They should be linked together, the way to link them is through this link

https: //developer.xamarin.com/guides/xamarin-forms/cloud-services/authentication/azure-ad-b2c-mobile-app/

现在,您应该可以正常通过MobileServiceClient访问您的简易表

Now you should be able to access your easy table normally through the MobileServiceClient

这篇关于使用Azure AD B2C登录到Xamarin Android应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆