What Redirect URL can I set for oauth2 callback in a chrome extension?
I want to use Imgur API in a chrome extension. The authentification response from user's input is sent to a "redirect url" set up in my application profile on the imgur web page.
How can I set that "redirect url" to point to the chrome browser extension of a user ?
I see only the heavy solution of setting up a tiny server to keep track of my users' tokens :
- My extension checks for an imgur token : if found, start extension workflow, else go to step 2.
- My extension asks the imgur api for its authentification form.
- the user fills the form, which is self-managed, and the form sends back its username/password to the imgur server.
- The Imgur server sends a query request containing the token to the 'redirect-url' specified.
- This 'redirect url' is my server url and it retrieve the token.
- [no idea how to do this step] the server and the extension exchange and the extension retrieves at least the precious token.
- With that token, the extension can at least display imgur pictures.
Their documentation mentions localhost as a possible url redirect. I am digging in this general direction but it fails to make sense to me : is seems to be more like about local test for developer than the answer I am looking for.
Thanks for any input.
Solution 1:
In most cases token gets appended to redirect url. So you can listen to tab update using chrome.tabs.onUpdated.addListener()
and check when tab url contains "access_token="
. Now it will listen to every tab. If you are creating authentication tab by yourself, you will get an id in its callback. Using this id you can check inside chrome.tabs.onUpdated.addListener()
callback that it is the same tab that you created or you can just match if tab url matches with redirect url. Both would work.
Example Code:
chrome.tabs.onUpdated.addListener(function authorizationHook(tabId, changeInfo, tab) {
if (tabId === authenticationTabId && tab.title.indexOf(redirectUrl) >= 0) {
//If you don't have the authentication tab id remove that part
if(tab.title.indexOf("access_token=") >=0){//tab url consists of access_token
var url = tab.title;
/*
Code to extract token from url
*/
chrome.tabs.onUpdated.removeListener(authorizationHook);
}
}
});
Also you would need "tabs"
permission for it to work
EDIT: You can also use chrome.identity.launchWebAuthFlow(). You would have to use :
Javascript origins: https://<extensionid>.chromiumapp.org
redirect url: https://<extensionid>.chromiumapp.org/provider_cb
Here is a great example of github-auth app which uses chrome.identity.launchWebAuthFlow()
. Same code can be used in extension.