【问题标题】:AngularJS and Google OAuth2 redirect_uriAngularJS 和 Google OAuth2 redirect_uri
【发布时间】:2016-10-29 02:09:27
【问题描述】:

我正在尝试使用 AngularJS 和 Google 的 OAuth2 来创建一个简单的应用程序进行身份验证。

由于弹出窗口阻止问题和移动友好性,我决定不使用Google APIs Client Library for JavaScript

这让我可以选择完全重定向到谷歌的OAuth2 endpoint,并使用 access_token 将用户重定向回我的应用程序。

我认为这会很好。重定向 URI 将是“http://myapp.com/#/register”,并附加一个“access_token”查询参数。然后我会使用 access_token 并将用户引导到我的应用程序中的其他位置。

这不起作用,因为 Google API 凭据 (http://developers.google.com/console) 不喜欢在重定向 URI 中包含“#”。

然后我尝试使用

关闭 URI 中的“#”要求
$locationProvider.html5Mode(true);

这也不起作用,因为我的 Angular 路由无法识别(在 Chrome 中)显式浏览到“http://myapp.com/register”。

对我应该如何实现这一点有什么想法吗?

【问题讨论】:

  • 您是否在您的 Web 服务器上使用 url 重写将 myapp.com/register 重写为 myapp.com
  • 不,我不是,只是使用简单的 IIS(与 IIS 一样简单:P)
  • 似乎您应该尝试一下 - 这样浏览到 myapp.com/register 确实有效。然后您的 Angular 应用程序处理将 /register 映射到正确的路由。具有使您的应用可深度链接的额外好处。

标签: javascript angularjs oauth-2.0 google-api


【解决方案1】:

以下对我有用,在我的应用中将 html5 模式设置为 true。

此代码进入重定向页面的控制器(确保注入 $window 服务):

//Get parameters from hash fragment
var params = {};
if ($window.location.hash.indexOf('#') === 0) {
    var regex = /([^&=]+)=([^&]*)/g, m;
    while (m = regex.exec($window.location.hash.substr(1))) {
        params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }
}

//Validate params, store access token etc.
if (!params.access_token) {
    //...
}

如果您的应用无法识别非 # 路由,请确保您的服务器启用了重写引擎,并将所有相关请求重定向到您的 Angular 应用主 HTML 文件。

【讨论】:

    【解决方案2】:

    如果你使用 IIS,你可以安装URL Rewrite 扩展。然后更新您的web.config 文件。例如,下面的配置会将所有内容重定向到您的 Angular 应用程序并让它处理路由。

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <system.webServer>
            <rewrite>
                <rules>
                    <rule name="Angular Default" stopProcessing="true">
                        <match url="(.*)" />
                        <action type="Rewrite" url="index.html" logRewrittenUrl="true" />
                    </rule>
                </rules>
            </rewrite>
        </system.webServer>
    </configuration>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-16
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 2020-05-22
      相关资源
      最近更新 更多