Home > Back-end >  How to enable a stay logged in feature in .NET MAUI?
How to enable a stay logged in feature in .NET MAUI?

Time:08-30

I want to utilise a stay logged-in in my .NET MAUI project for the user when they log into my app. I have the admin data binding done, so it saves the user and adds validation on log-in, but I don't know how to make the user stay logged in after closing the app.

This is my Log in so far.

 public partial class LoginViewModel : ObservableObject
    {
        [ObservableProperty]
        string userName;

        [ObservableProperty]
        string password;

        [ObservableProperty]
        string errorDisplay;

        [RelayCommand]
        public async Task LoginVerification()
        {

            bool search = await App.StaffService.AdminStaffLoginAuth(UserName, password);

            if (search)
            {
                Debug.WriteLine("User Was Found");
                ErrorDisplay = "should navigate";
                await Shell.Current.GoToAsync("/Dashboard");
            }
            else
            {
                Debug.WriteLine("User Not Found");
                ErrorDisplay = "Invalid username or password";
            }
        }

    }

And here is my front-end to call a logged-in function

<Label Text="Stay Logged In" FontFamily="PoppinsMedium" FontSize="18" TextColor="#102D4C" Margin="0, 10, 0, 0"/>
                     <Switch IsToggled="{Binding StayLoggedOn}" Margin="10, 7, 0, 0" OnColor="#FEEED8" ThumbColor="#FE5A22"/>

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