如何从 Xamarin / Android webview localstorage 接收当前访问令牌?

How to receive current access token from Xamarin / Android webview localstorage?

我目前正在我的 Xamarin Forms 应用程序上使用自定义 webview。我需要与需要 return 值的访问令牌的 api 进行通信。到目前为止一切顺利,我能够登录,通过回调接收我的登录数据,包括我的第一次访问和刷新令牌,并将其存储在智能手机上的 sqlite 数据库中。 但是我如何才能注意到访问令牌是否发生了变化?

由于我只在登录时存储了访问令牌,如果 webview 会话使用刷新令牌更新访问令牌,我该如何应对?

我的本机 api 调用需要新令牌,无需新登录,因为 webview 刷新访问令牌我想从我的 webview 本地存储接收当前访问令牌。

有没有办法从 webview 本地存储中获取当前访问令牌?

一般我们在使用过时的token请求时API,后台服务器会对请求的token进行校验。如果token过期,会return相应的反馈数据,然后APP会弹出用户提示:Token expired, please login again.。 然后APP会跳转到登录页面,重新登录获取最新的token。

更新 1:

嗯,由于Token只能在登录时获取,所以当你请求API发现token过期时,你可以重新登录获取最新的token。

但我们不推荐这样做,因为它违背了令牌的目的之一:Using for authentication。 比如一个用户登录后长时间不使用,而另一个别有用心的人拿到phone并使用该APP,他就可以成功使用该APP并获取一些隐私信息,甚至如果令牌过期。

更新二:

是的,可以获取存储在 LocalStorage 中的 userKey 字段。 比如你想获取存储在LocalStorage中的userKey字段,你可以这样做:

1.Write一个接受Js回调的接口

  public class MyJSInterface : Java.Lang.Object, Java.Lang.IRunnable
{
    Context context;
    public MyJSInterface(Context context)
    {
        this.context = context;
    }

    [JavascriptInterface]
    [Export]
    public void Run()
    {
        Toast.MakeText(context, "Hello from C#", ToastLength.Short).Show();
    }
}

2.Add 到 WebView 并重命名为 "shixintest" :

  mWebView.AddJavascriptInterface(new MyJSInterface(this), "shixintest");

3.call JS

  private void getLocalStorageUserKey()
    {
        if (mWebView != null && TextUtils.IsEmpty(APPEnvironment.GetBeforeLoginUserKey()))
        {
            mWebView.LoadUrl(
        "javascript:(function(){
            var localStorage = window.localStorage; window.shixintest.getUserKey(localStorage.getItem('userKey'))})()");
    }