How do you do OAuth2 in cordova/phonegap apps?
I have been asked this question multiple times in the last few years, and I always just sort of dismissed it as being easy. I would typically say ‘Use the InAppBrowser plugin and watch for location changes.’ A recent pull-request to the InAppBrowser asking to add potentially unsecure Android intent/protocol support tells me I need to do a bit more to explain and show how this works.
Here is what I meant when I dismissed this as trivial:
var endUrl = "https://phonegap.com/authCallback";
var startUrl = "http://github.com/login/oauth/authorize/";
startUrl += "?client_id=89855411f5d2ab238ad2";
startUrl += "&redirect_uri=" + endUrl;
// scope, state, allow_signup also available
var browser = cordova.InAppBrowser.open(startUrl, '_blank', 'location=yes');
browser.addEventListener('loadstart', function(evt){
console.log('evt.url = ' + evt.url);
if(evt.url.indexOf(endUrl) == 0) {
// close the browser, we are done!
browser.close();
// TODO: pull the token out and
// use it for further API calls.
}
});browser.addEventListener('loaderror', function(err) {
console.log("error " + err);
// TODO: handle this of course!
});
Of course, you will need the InAppBrowser plugin installed for this to work, but it’s pretty easy right?
Just in case you would like it easier still, I have thrown together a plugin that does it for you. Here is how you can accomplish the same thing with the plugin:
var endUrl = "https://phonegap.com/authCallback";
var startUrl = "http://github.com/login/oauth/authorize/";
startUrl += "?client_id=89855411f5d2ab238ad2";
startUrl += "&redirect_uri=" + endUrl;
// scope, state, allow_signup also available PG_OAuth2.authenticate(function(url){
// TODO: pull the token out and use it for further API calls.
},
function(err) {
// TODO: handle this of course
}, startUrl,endUrl);
});
Install the plugin like this:
cordova plugin add https://github.com/purplecabbage/phonegap-plugin-oauth2
( I’ll get it on npm soonish )
As always, I welcome your comments, critiques, issues, and of course pull requests.
Cheers!
-J