在xamarin.form应用程序中存储令牌的位置

use*_*476 4 xamarin.forms

我在下面的类中将使用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)

Sha*_*raj 23

令牌是敏感信息,我建议以安全的方式存储它们.安全存储可通过KeychainiOS中的服务和KeyStoreAndroid中的类来获得.Xamarin有一篇关于如何使用它的非常好的文章Xamarin.Auth.

其他选择包括:

  1. BlobCache.SecureAkavache
  2. SecureStorage
  3. XLabs中安全存储


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)


Jas*_*son 6

Forms 有一个内置的Properties字典,您可以在其中存储少量持久数据。

Application.Current.Properties ["token"] = myToken;
Run Code Online (Sandbox Code Playgroud)