Xamarin Auth帐户商店

时间:2018-05-01 19:26:02

标签: xamarin oauth xamarin.forms xamarin.auth

我正在尝试使用我的应用程序实现Xamairn Auth。我已经从https://www.nuget.org/packages/Xamarin.Auth安装了nuget包。

按照他们的示例,我在共享项目中有以下代码。

public void SaveCredentials (string userName, string password)
{
  if (!string.IsNullOrWhiteSpace (userName) && !string.IsNullOrWhiteSpace (password)) {
    Account account = new Account {
      Username = userName
    };
    account.Properties.Add ("Password", password);
    AccountStore.Create ().Save (account, App.AppName);
  }
}

在Android上运行时,会保存用户名和密码,但我在控制台中收到以下消息:

由于默认密码,此版本不安全。 请使用提供AccountStore密码的版本。 AccountStore.Create(Contex,string)或AccountStore.Create(string);

我尝试将参数传递给AccountStore.Create()方法,但似乎没有一个参数。像这样:

#if ANDROID
   _accountStore = AccountStore.Create(Application.Context);
#else
   _accountStore = AccountStore.Create();
#endif

我是否需要编写特定于Android的代码来扩展create方法。

2 个答案:

答案 0 :(得分:1)

我理解为什么你删除了非答案,我认为这会对问题表示出兴趣。我想我应该反过来提出这个问题。无论如何,这是我找到的答案。

您无法使用PCL版本的Android。它没有添加密码的选项。我使用了Android特定版本。将使用依赖服务调用它。

以下是一个例子:

    Account account = null;

    try
    {
        //account = AccountStore.Create(Application.ApplicationContext, "System.Char[]").FindAccountsForService("My APP").FirstOrDefault();             
        var aStore = AccountStore.Create(Application.ApplicationContext, "myownpassword");

        // save test
        account = aStore.FindAccountsForService(Constants.AppName).FirstOrDefault();
        if (account == null)
            account = new Account();
        account.Username = "bobbafett";
        account.Properties["pswd"] = "haha";
        aStore.Save(account, Constants.AppName);

        // delete test, doesn't seem to work, account is still found
        var accts = aStore.FindAccountsForService(Constants.AppName);
        int howMany = accts.ToList().Count;
        foreach (var acct in accts)
        {
            aStore.Delete(acct, Constants.AppName);
        }
        account = aStore.FindAccountsForService(Constants.AppName).FirstOrDefault();
    }
    catch (Java.IO.IOException ex)
    {
        // This part is not invoked anymore once I use the suggested password.
        int i1 = 123;
    }

答案 1 :(得分:0)

我能够通过在android中实现getAccountStore方法来实现它,该方法可以选择添加密码,然后使用DependencyService来调用它。

public AccountStore GetAccountStore()
{
    try
    {
        var acctStore = AccountStore.Create(Application.Context, "somePassword");
        return acctStore;
    }
    catch (Java.IO.IOException ex)
    {
        throw ex;
    }
}

然后在你的pcl项目中调用它:

 if (Device.RuntimePlatform == Device.Android)
   _accountStore = DependencyService.Get<IAccountStoreHelper>().GetAccountStore();
else
   _accountStore = AccountStore.Create();