Search code examples
androidxamarinwebviewlocal-storageaccess-token

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


i am currently using a custom webview on my Xamarin Forms App. I need to communicate with an api that needs an access token to return values. So far so good, I am able to login, receive my login data including my first access and refresh token via callback and store it on the smartphone in a sqlite database. But how can I notice if the access token changes?

Since I have only stored the access Token on login, how can I react if the session of the webview updates the access token with the refresh token?

I need the new token for my native api calls, without a new login, since the webview refreshes the access token I somehow want to receive the current access token from my webview local storage.

Is there any way to grab the current access token from the webview local storage?


Solution

  • Generally, when we use the outdated token request API, the background server will verify the token requested. If the token expires, it will return the corresponding feedback data, and then the APP will pop up the user with such tips as: Token expired, please login again.. Then the APP will jump to the login page and login again to get the latest token.

    Update 1:

    Well, since Token can only be obtained at login time, so when you request a API and find the token has expired, you can login again and abtain the latest token.

    But we don't recommend this ,because it defeats one of the purpose of token:Using for authentication. For example, if a user logs in and doesn't use it for a long time, and another person with ulterior motives get the phone and use the APP, he can successfully use the APP and get some private information, even if the token expires.

    Update 2:

    Yes, it is possible to get the userKey field stored in LocalStorage. For example, if you want to get the userKey field stored in LocalStorage, you can do like this:

    1.Write an interface to accept Js callbacks

      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 to WebView and rename to "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'))})()");
        }