Authentication using Apache Cordova for Visual Stu

2020-04-20 12:30发布

问题:

I am working on a cross-platform Twitter app using Cordova in Visual Studio and I am stuck at the authentication of twitter account.
When targeting Windows/Windows Phone, I can use Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync API and get the work done. But for Android or IOS I can't use the API as it is complaining that Windows is undefined.

Could someone help me with a sample code or suggestion on how should I be doing authentication using JavaScript ?

回答1:

I think you shouldn't rely on a Windows API on a cross-platform app, as it won't be available on any other platform than Windows. Instead you may want to authenticate with a javascript solution that works on every platform.
There are several possibilities doing this in js, depending on what frameworks and libraries you're using in your app: You may authenticate using $.ajax if you're using jquery or the $http service if you're using angular... If you're not using any library you could use a XMLHttpRequest.



回答2:

I found a solution using InAppBrowser plugin from Cordova.

Add the plugin to your project and then have the code below to authorize your app.

var self = this;
var ref = cordova.InAppBrowser.open(startURI, '_blank', 'location=yes');
ref.show();    
ref.addEventListener('loadstart', function (event) {
   if (event.url && event.url.match('oauth_verifier'))
   {                            
       ref.close();
       self._continueAuthentication(event.url, callback);
   } 
});

ref.addEventListener('loadstop', function (event) {
});

ref.addEventListener('exit', function (response) {
});

_continueAuthentication: function (returnedTokens, callback) {
        var self = this, oauthVerifier, oauthToken;
        var responseKeyValPairs = returnedTokens.split("?")[1].split("&");

        //Disect the important parts
        for (i = 0; i < responseKeyValPairs.length; i++) {
            splits = responseKeyValPairs[i].split("=");
            switch (splits[0]) {
                case "oauth_verifier":
                    oauthVerifier = splits[1];
                    break;
                case "oauth_token":
                    oauthToken = splits[1];
                    break;
       }
}