2017-09-01 87 views
0

我有一个类将在xamarin.forms移动应用程序 中用于检索由OAuth(webapi)生成的令牌。一旦产生这种情况,我需要将 存储在我可以再次访问它的地方,而不是一直生成。 最好的地方在Pcl中存储这个地方在哪里?我还希望能够删除此用户注销一次 。在xamarin.form应用程序中存储令牌的位置

 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); 
       } 
      } 
     } 

回答

0

表格内置Properties字典,您可以在其中存储小量的持久数据。

Application.Current.Properties ["token"] = myToken; 
+0

那么这将会在PCL应用?如果用户关闭应用程序会发生什么?价值会丢失吗? – user2320476

+0

是的,你在共享项目中使用它。它会自动持续 - 我建议你阅读我链接到的文档。 – Jason

3

令牌是敏感信息,我建议将它们以安全的方式存储。安全存储可通过iOS中的Keychain服务和Android中的KeyStore类获得。 Xamarin在使用Xamarin.Auth时如何做到这一点非常好article

其它选项有:

  1. BlobCache.SecureAkavache
  2. SecureStorage
  3. 安全存储在XLabs
相关问题