javascript 如何通过打开新窗口而不是从当前页面重定向用户来执行 OAuth 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7606071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:41:02  来源:igfitidea点击:

How can I do OAuth request by open new window, instead of redirect user from current page?

javascriptfacebooktwitterpopup

提问by Hoàng Long

I have done OAuth authentication with Twitter and Facebook. Currently, with each of these site, my server redirect user to a specified URL (for example, http://api.twitter.com/oauth/authorizewith Twitter), then receive authentication parameters by callback url.

我已经使用 Twitter 和 Facebook 完成了 OAuth 身份验证。目前,对于这些站点中的每一个,我的服务器将用户重定向到指定的 URL(例如,http://api.twitter.com/oauth/authorizewith Twitter),然后通过回调 url 接收身份验证参数。

But by that way, the users get redirected out of my page (to Facebook or Twitter), and only returns after input correct username & password. It's like the way http://techcrunch.comdo it when a user try to tweet a post.

但是通过这种方式,用户会被重定向出我的页面(到 Facebook 或 Twitter),并且只有在输入正确的用户名和密码后才会返回。这就像当用户尝试发布帖子时http://techcrunch.com 的做法。

I remember that in some site, I have seen that we can connect not by redirect user out, but open a popup window for user to input credentials instead. After authentication is completde, the pop-up closed, the main page refresh with new content.

我记得在某些站点中,我看到我们不能通过将用户重定向出去来连接,而是打开一个弹出窗口供用户输入凭据。验证完成后,弹出窗口关闭,主页面刷新为新内容。

This could be a very simple task with javascript, but I still can't figure it out. I can open authentication URL in a pop-up window, but how to get the result & update the main page?

这可能是使用 javascript 的一项非常简单的任务,但我仍然无法弄清楚。我可以在弹出窗口中打开身份验证 URL,但如何获取结果并更新主页?

回答by WTK

Assuming you're opening authentication url in a pop-up using window.open(), you can access parent window by using:

假设您在使用 的弹出窗口中打开身份验证 url window.open(),您可以使用以下方法访问父窗口:

window.opener

and to reloadparent window (from a pop-up) use:

重新加载父窗口(从弹出窗口)使用:

window.opener.location.reload();

This code should be served on url that you've set up as success callback url of oauth authorization.

此代码应在您设置为 oauth 授权的成功回调 url 的 url 上提供。

In general, the flow should be:

一般来说,流程应该是:

  • open a pop-up with an authorization page (on twitter.com for example)
  • after successfull authorization twitter redirects user to url given by you (it gets opened in the very same pop-up)
  • the opener window gets reloaded (via window.opener.location.reload())
  • close the pop-up itself (using javascript is you want)
  • 打开一个带有授权页面的弹出窗口(例如在 twitter.com 上)
  • 成功授权后,twitter 将用户重定向到您提供的 url(它在同一个弹出窗口中打开)
  • 开启器窗口被重新加载(通过window.opener.location.reload()
  • 关闭弹出窗口本身(使用 javascript 是你想要的)