Reputation: 2229
I have the class below that will be used in a xamarin.forms mobile application to retrieve the token generated by OAuth(webapi). Once this is generated I need to store in a place where I can access it again and not generating this all the time. Where is the best place to store this in the Pcl? I will also want to be able to remove this once the user logs off.
class LoginService
{
public async Task Login(string username, string password)
{
HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}Token", Constants.BaseAddress)));
request.Method = "POST";
string postString = String.Format("username={0}&password={1}&grant_type=password",
HttpUtility.HtmlEncode(username), HttpUtility.HtmlEncode(password));
byte[] bytes = Encoding.UTF8.GetBytes(postString);
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(bytes, 0, bytes.Length);
}
try
{
HttpWebResponse httpResponse = (HttpWebResponse)(await request.GetResponseAsync());
string json;
using (Stream responseStream = httpResponse.GetResponseStream())
{
json = new StreamReader(responseStream).ReadToEnd();
}
TokenResponseModel tokenResponse = JsonConvert.DeserializeObject(json);
return tokenResponse.AccessToken;
}
catch (Exception ex)
{
throw new SecurityException("Bad credentials", ex);
}
}
}
Upvotes: 17
Views: 13462
Reputation: 889
Just an update for anyone searching, as things have changed since this post was created. It is not advised to use the following any more:
Application.Current.Properties
To securely store things like access tokens etc you can use the Xamarin.Essentials SecureStorage static class.
Just add the Xamarin.Essentials nuget package if you don't already have it and use it like so:
using Xamarin.Essentials;
.
.
.
await SecureStorage.SetAsync("someKey", "someValue");
var myValue = await SecureStorage.GetAsync("someKey");
you also have the option to
SecureStorage.Remove("someKey");
//or
SecureStorage.RemoveAll();
Refer this for more documentation
Upvotes: 21
Reputation: 13601
Token(s) being sensitive information, I would recommend storing them in a secure manner. Secure storage is available through Keychain
services in iOS, and the KeyStore
class in Android. Xamarin has a very good article on how to do that using Xamarin.Auth
.
Other options available are:
BlobCache.Secure
in AkavacheUpvotes: 28
Reputation: 89129
Forms has a built in Properties dictionary where you can store small bits of persistent data.
Application.Current.Properties ["token"] = myToken;
Upvotes: 6