简体   繁体   中英

Cross-Domain OAuth… how to get response?

I'm creating a Chrome Extension which will interact with a particular popular website.

It injects html into the site which adds new features. Parts of these features depend on the user being logged in, and in order to get that logged in user information, we need to to authenticate the extension with this website's OAuth authentication API.

For example, lets say the popular site (that we don't own, obviously) is www.github.com .

When the user is on www.github.com, our extension injects a button that says 'Connect with GitHub' on the site.

When that button is clicked, and a popup opens to Githubs OAuth API, and it asks the user: 'Do you want to give the app XYZ access to your GitHub account? Yes / No'.

Once they hit yes, our extension is authenticated and can now use the GitHub API to access information like their username and such, and inject it right into the github.com website.

All this is how we want it to work, but the problem is we're having a lot of difficulty communicating between the current window ( www.github.com ) and the popup window of our own server ( www.server.com ).

The Oauth success callback which happens in the popup, that returns the token, we can't communicate it back to the main page, because the 'protocols, domains, and ports' don't match.

What is the best way to capture that token from inside the popup oauth success window, so that we can use this token in our extension, which sits on the other domain?

How about the following: In the final stage of the auth flow you can redirect to server.com . Since you own server.com you can inject a script at the end that passes data to the extension via window.opener.postMessage

For example, in the final page rendered by server.com :

window.opener.postMessage({"userhash": "abc1234567890"}, '*');

Then register an event listener on the window in the extension

window.addEventListener('message', function(e) {
  console.log(e.data);
});

This should work in both chrome and firefox.

Maybe you can't get a response because Chrome has a "Same origin policy". https://en.wikipedia.org/wiki/Same-origin_policy

Normally you can get around that by letting your www.server.com put www.github.com in the Access-Control-Allow-Origin header in the response.

See also the answer to this question for an example: How does Access-Control-Allow-Origin header work?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM