我在尝试使用 OAuth(在 Knockout.js 中)将 Web Api SPA 模板重写为 AngularJS 时陷入了这一问题。
当我单击外部登录按钮时,会发生一系列请求,最终导致
Authentication.SignIn(claimsIdentity);
这很好!但是,在我返回 Ok()
之后,我被重定向到外部登录 (Google)。我登录 Google 后,他们的授权服务器会响应 302 重定向至以下位置:
http://localhost:59936/access_token=xxxx&token_type=bearer&expires_in=1209600&state=yyyy
查看淘汰赛中的 SPA 模板,我应该解析 token 的 URL,并使用访问 token 调用 getUserInfo()
。
然而,发生的情况是该链接被塞到我的浏览器 URL 栏中,而 Angular 却没有注意到它。我的 httpInterceptor
没有触发,$routeChanged
也没有触发,我认为这很愚蠢/肮脏/并且可能无法创建 $routeProvider。当(“/access_token”)
我使用的是 1.2.9 Angular(我看到有人提到了 Angular 中的一个错误,我找不到关于它的 http 拦截器
处理 302 的错误,而且它是1.2.9 中已修复,但情况似乎并非如此。
要做什么?
编辑:实际上,考虑一下代码的结构,使用 routeProvider
捕获代码实际上并没有那么脏。这是因为 HomeController
看起来像这样:
function HomeController(...) {
//Parses the url above
var fragment = getFragment();
... All kinds of fragment checks (fragment.access_token, fragment.state, etc)...
}
问题是当这个 URL 被填充到浏览器中时,HomeController
没有被实例化。
有什么方法可以将上面的 URL 与路由匹配吗?类似于 when('/access_token*rest')
——但这不起作用。
我能想到的一个潜在的解决方法是捕获 $locationChangeStart
中的 URL 更改并将 access_token
填充到本地/ session 存储中,但这需要大量代码重组,因为所有逻辑都已经在 HomeController
中。最好的方法是在该 URL 被点击时实例化它。
不令人满意的解决方法:这是另一个解决方法,但我真的对此不满意。它很糟糕,需要大量的重组。
app.run(['$rootScope', '$location', '$http', '$controller', 'AuthenticationService',
'$window', 'StorageService', //HomeController Dependencies
function ($rootScope,
$location,
$http,
$controller,
AuthenticationService,
$window, StorageService)
{
$rootScope.$on("$locationChangeStart", function (event, next, current) {
if (next.indexOf("access_token") > -1) {
var homeController = $controller(Controllers.Authentication.HomeController, {
'$rootScope': $rootScope,
'$scope': {},
'$window': $window,
'$location': $location,
'AuthenticationService': AuthenticationService,
'StorageService': StorageService
});
}
});
}
最佳答案
Is there any way to match the above url to a route? Something like when('/access_token*rest') --However this does not work.
如果您的 URL 是 http://localhost:59936/?access_token=xxxx&token_type=bearer&expires_in=1209600&state=yyyy
(注意添加的 ?
),那么路由器可以匹配就像这样 $routeProvider.when('/')
(因为路由器会忽略参数字符串),然后在你的 Controller 中你可以解析 url 参数。
此外部登录是否会导致包含您的 Angular 应用程序的页面重定向到外部网页?如果是这种情况,那么您的应用程序将被卸载,这可能并不理想。为了处理外部登录,我通常会打开一个弹出窗口,这样我的应用程序就不会被卸载。
关于angularjs - 带有 Angular 前端的 Web Api OAuth - 无法处理 302 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21501305/