简体   繁体   中英

Default user implementation in Xamarin Forms to auto login

I have created my first Xamarin.Forms application using Xamarin Studio. My application is not able to remember the default username, so that user has to login app every time which is irritating. How can I store the last user credentials to auto login, if he/she has not logged out to from the app? Is it possible in PCL?

Method 1:

Use SettingsPlugin to store the user credentials as you required. This will help to access settings from PCL across all of your mobile apps.

public static class Settings 
{

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

    //Setting Constants

    const string UserName = "username";
    private static readonly string UserNameDefault = string.Empty;

    public static string UserName
    {
        get { return AppSettings.GetValueOrDefault<string>(UserName, UserNameDefault); }
        set { AppSettings.AddOrUpdateValue<string>(UserName, value); }
    }

    const string Password = "password";
    private static readonly string PasswordDefault = string.Empty;

    public static string Password
    {
        get { return AppSettings.GetValueOrDefault<string>(Password, PasswordDefault); }
        set { AppSettings.AddOrUpdateValue<string>(Password, value); }
    }
}

For autologin create a blank page as splash screen page. Set it to as :

Application.Current.MainPage = new MySplashScreen();

On the behind code of this page :

public partial class MySplashScreen : ContentPage
{
 public MySplashScreen()
    {
         InitializeComponent();

         CheckForAutoLogin();
     }

private async void CheckForAutoLogin()
  {
    if (Settings.UserName != string.Empty && Settings.Password != string.Empty)
       {
           //Redirect to you desired page
       }

    else
       {
           //Redirect to login page.
       }
  }
}

So in above implementation, I have created a temporary page as splash screen just to check for login credential and accordingly redirect to the desired page.

So if you use this Plugin then it is not recommended, to store password like values in string format. For that you need to make use of any encryption/decryption algorithm and then store the encrypted value using Settings.Plugin.

Method 2:

You can use Xamarin.Auth (Cross-Platform SDK). It is a secure way to store your credential. It is a cross-platform SDK for authenticating users and storing their accounts. It can be used to securely store Account objects in an account store so that applications do not always have to re-authenticate users.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM