Home > database >  How to make an autologin system in .NET MAUI?
How to make an autologin system in .NET MAUI?

Time:08-30

I want users to be able to automatically login into my .NET MAUI app.

I have the login system done, but I don't know how to make the login persistent once they close the app.

This is my login system so far.

 public partial class Login
    {
        // User credentials
        string username;
        string password;

        // Try verification
        public async Task LoginVerification()
        {
            // Check if credentials are valid in the database.
            bool isValid = await CheckIfValid(username, password);

            if (isValid)
            {
                Debug.WriteLine("User Was Found");
                // Do stuff after succesful login.
            }
            else
            {
                Debug.WriteLine("User Not Found");
                // Do stuff after unsuccesful login.
            }
        }

    }

How can I make it so they don't have to enter their credentials the next time they launch the application?

CodePudding user response:

This is typically achieved by saving the user's login data and then performing an automatic login when necessary. This also ensures the credentials are still valid.

I recommend saving such data to .NET MAUI Preferences system.

This works with Key-Value pairs that are saved to the app's data.

This is an example of saving the user's password to the user's preferences.

// Create the password string
string myPass = "somePass";

// Save the password to the Preferences system
Preferences.Set("UserPassword", myPass); // The first parameter is the key

After saving the user's data to the app's preferences, you can retrieve it on app startup and perform an automatic login by using the Get() method.

// Get the password from the Preferences system
string passwordFromPrefs = Preferences.Get("UserPassword", "defaultPass");

Note that the Get() method requires you to pass a second argument for the default value. In case there is no data for the specified key in the app's preferences, the method will return this default value.

  • Related