Storing and Retrieving User Credentials in Xamarin

2019-06-14 17:06发布

问题:

I have a Xamarin.iOS application that requires users to log-in in order to view content. I have two text fields, one for username and one for password. Once a user has logged in and the API has returned success. how can I save the users credentials so when they launch the app they get signed in automatically?

I tried this, however, I don't know how to retrieve the values or re-save credentials if user logs out

void StoreKeysInKeychain(string key, string value)
    {

        var s = new SecRecord(SecKind.GenericPassword)
        {
            ValueData = NSData.FromString(value),
            Generic = NSData.FromString(key)
        };
        var err = SecKeyChain.Add(s);
    }

Thanks.

回答1:

Better to use iOS default NSUserDefaults.StandardUserDefaults to store your credentials.

Check for stored value in Login ViewController, if it doesn't exist then after successful login set the user name and password to "GetStoredCredentials" else fetch the saved credentials and use.

public String GetStoredCredentials
{
    get { 
        string value = NSUserDefaults.StandardUserDefaults.StringForKey("Key"); 
        if (value == null)
            return "";
        else
            return value;
    }
    set {
        NSUserDefaults.StandardUserDefaults.SetString(value.ToString (), "Key"); 
        NSUserDefaults.StandardUserDefaults.Synchronize ();
    }
}

Either you can save as string array or comma seperated value. Let me know for any further assistance. For your refrence : https://developer.xamarin.com/guides/ios/application_fundamentals/user-defaults/



回答2:

You can install this plugin and all of the work is already done for you: https://github.com/sameerkapps/SecureStorage, nuget: https://www.nuget.org/packages/sameerIOTApps.Plugin.SecureStorage/.

If you use the plugin it is as simple as:

CrossSecureStorage.Current.SetValue("SessionToken", "1234567890");
var sessionToken = CrossSecureStorage.Current.GetValue ("SessionToken");

If you don't want to use it, then look into github repo and see how they did it for iOS: https://github.com/sameerkapps/SecureStorage/blob/master/SecureStorage/Plugin.SecureStorage.iOSUnified/SecureStorageImplementation.cs

public override string GetValue(string key, string defaultValue)
{
    SecStatusCode ssc;
    var found = GetRecord(key, out ssc);
    if (ssc == SecStatusCode.Success)
    {
        return found.ValueData.ToString();
    }

    return defaultValue;
}

private SecRecord GetRecord(string key, out SecStatusCode ssc)
{
    var sr = new SecRecord(SecKind.GenericPassword);
    sr.Account = key;
    return SecKeyChain.QueryAsRecord(sr, out ssc);
}