2017-09-01 84 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
相關問題