如何让用户登录xamarin

时间:2016-12-07 17:50:38

标签: c# android azure xamarin.android xamarin.forms

您好我正在尝试存储用户登录xamarin应用程序。

官方教程讨论如何登录而不是如何保持用户登录。 Microsoft Tutorial xamarin Tutorial

我的问题是每次重新启动应用程序时都必须运行Login方法,这会在它关闭之前显示一段空白屏幕。

登录方式

async void Login()
        {
            if(App.Authenticator != null && authenticated == false)
            {
                authenticated = await App.Authenticator.Authenticate();
            }
        }

验证方法

public async Task<bool> Authenticate()
        {
            var success = false;
            var message = string.Empty;

            try
            {

                    //Sign in with Active Directory Service
                user = await ShopItemManager.DefaultManager.CurrentClient.LoginAsync(this,
                    MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory);



                if (user != null)
                {
                    message = string.Format("You are now signed in as {0}", user.UserId);
                    success = true;
                    //store token
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }

            //Display the success or failure message
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.SetMessage(message);
            builder.SetTitle("Sign-in Result");
            builder.Create().Show();

            return success;
        }

3 个答案:

答案 0 :(得分:0)

对Xamrin不太了解,但在原生android中,我们使用SharedPreferences来保存登录状态。在Android中使用SharedPreferences来预先存储一些数据(即在关闭应用程序之后,它将持续存在)。我们可以设置一个布尔值来检测用户是否在下次启动时成功登录。

SharedPreferences相当的Xamarin.Android是一个名为ISharedPreferences的界面。

以相同的方式使用它,您将能够轻松地移植Android代码。

例如,要使用某些bool保存真/假Context,您可以执行以下操作:

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
ISharedPreferencesEditor editor = prefs.Edit ();
editor.PutBoolean ("key_login_successfully", true);
// editor.Commit();    // applies changes synchronously on older APIs
editor.Apply();        // applies changes asynchronously on newer APIs

使用以下方式访问已保存的值:

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
mBool = prefs.GetBoolean ("key_login_successfully", <default value>);

从这个示例中,您可以看到,一旦您知道要使用的正确C#接口,其余的就很容易了。关于如何在更复杂的情况下使用SharedPreferences,有许多Android java示例,可以使用ISharedPreferences轻松移植这些示例。

有关更多信息,请阅读以下主题:

答案 1 :(得分:0)

所以This tutorial有信息。这有点牵扯。

此代码存储密钥。另一个用户的确提到了哪个。虽然这是跨平台的。     公共静态类设置     {         private static ISettings AppSettings =&gt; CrossSettings.Current;

    const string UserIdKey = "userid";
    static readonly string UserIdDefault = string.Empty;

    const string AuthTokenKey = "authtoken";
    static readonly string AuthTokenDefault = string.Empty;

    public static string AuthToken
    {
        get { return AppSettings.GetValueOrDefault<string>(AuthTokenKey, AuthTokenDefault); }
        set  { AppSettings.AddOrUpdateValue<string>(AuthTokenKey, value); }
    }

    public static string UserId
    {
        get { return AppSettings.GetValueOrDefault<string>(UserIdKey, UserIdDefault);  }
        set { AppSettings.AddOrUpdateValue<string>(UserIdKey, value); }
    }

    public static bool IsLoggedIn => !string.IsNullOrWhiteSpace(UserId); 
}

但是,当使用客户端构造函数传递时,此Auth处理程序将确保在保存任何存储的凭据时使用它们。

    class AuthHandler : DelegatingHandler
{
    public IMobileServiceClient Client { get; set; }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (this.Client == null)
        {
            throw new InvalidOperationException("Make sure to set the 'Client' property in this handler before using it.");
        }

        // Cloning the request, in case we need to send it again
        var clonedRequest = await CloneRequest(request);
        var response = await base.SendAsync(clonedRequest, cancellationToken);

        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            // Oh no! user is not logged in - we got a 401
            // Log them in, this time hardcoded with MicrosoftAccount but you would
            // trigger the login presentation in your application
            try
            {
                var user = await this.Client.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount, null);
                // we're now logged in again.

                // Clone the request
                clonedRequest = await CloneRequest(request);


                Settings.UserId = user.UserId;
                Settings.AuthToken = user.MobileServiceAuthenticationToken;

                clonedRequest.Headers.Remove("X-ZUMO-AUTH");
                // Set the authentication header
                clonedRequest.Headers.Add("X-ZUMO-AUTH", user.MobileServiceAuthenticationToken);

                // Resend the request
                response = await base.SendAsync(clonedRequest, cancellationToken);
            }
            catch (InvalidOperationException)
            {
                // user cancelled auth, so let’s return the original response
                return response;
            }
        }

        return response;
    }

    private async Task<HttpRequestMessage> CloneRequest(HttpRequestMessage request)
    {
        var result = new HttpRequestMessage(request.Method, request.RequestUri);
        foreach (var header in request.Headers)
        {
            result.Headers.Add(header.Key, header.Value);
        }

        if (request.Content != null && request.Content.Headers.ContentType != null)
        {
            var requestBody = await request.Content.ReadAsStringAsync();
            var mediaType = request.Content.Headers.ContentType.MediaType;
            result.Content = new StringContent(requestBody, Encoding.UTF8, mediaType);
            foreach (var header in request.Content.Headers)
            {
                if (!header.Key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase))
                {
                    result.Content.Headers.Add(header.Key, header.Value);
                }


   }
    }

    return result;
}
}

答案 2 :(得分:0)

要实现此目的,您可以使用xamarin settings plugin,请按照以下步骤操作。

  1. 安装设置插件。
  2. 添加设置类。
    public static class SettingsHelper
    {

        private static ISettings AppSettings
        {
            get
            {
                return CrossSettings.Current;
            }
        }

        #region Setting Constants

        private const string LoginKey = "login_key";
        private static readonly string SettingsDefault = string.Empty;

        #endregion


        public static string GeneralSettings
        {
            get
            {
                return AppSettings.GetValueOrDefault(LoginKey, SettingsDefault);
            }
            set
            {
                AppSettings.AddOrUpdateValue(LoginKey, value);
            }
        }
    }
  1. 内部登录方法设置值设置为GeneralSettings,下次打开应用程序时,检查常规设置值并相应地分配导航。