我在下面的类中将使用xamarin.forms移动应用程序来检索由OAuth(webapi)生成的令牌.一旦生成了这个,我需要存储在我可以再次访问它的地方,而不是一直生成它.在Pcl中存放这个的最佳位置在哪里?我还希望能够在用户注销后删除它.
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Cra*_*aig 14
只是对任何搜索者的更新,因为自这篇文章创建以来情况发生了变化。不建议再使用以下内容:
Application.Current.Properties
Run Code Online (Sandbox Code Playgroud)
要安全地存储访问令牌等内容,您可以使用Xamarin.Essentials SecureStorage静态类。
如果您还没有Xamarin.Essentials nuget 包,只需添加它并像这样使用它:
using Xamarin.Essentials;
.
.
.
await SecureStorage.SetAsync("someKey", "someValue");
var myValue = await SecureStorage.GetAsync("someKey");
Run Code Online (Sandbox Code Playgroud)
您还可以选择
SecureStorage.Remove("someKey");
//or
SecureStorage.RemoveAll();
Run Code Online (Sandbox Code Playgroud)
Forms 有一个内置的Properties字典,您可以在其中存储少量持久数据。
Application.Current.Properties ["token"] = myToken;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5346 次 |
| 最近记录: |