在 Durandal 单页应用程序中使用 OAuth2 进行身份验证

Authenticating with OAuth2 in a Durandal single page application

我有一个使用 Durandal 的单页应用程序。在其中一个页面上,我需要使用 OAuth 2 进行身份验证以获取用于调用 Web 服务的令牌。我不想丢失我的单页应用程序状态,所以我想在新的 window.

中执行 OAuth 授权

我现在遇到的未解决问题是将 OAuth 令牌从子 window 传递给父。我试图找到一种方法将令牌从子 window 放入父 window 中的 Durandal 应用程序,但我还没有找到任何解决方案。最后我决定把它放在父 window 的 属性 中,但它仍然不起作用。

这是我的模块代码:

activate: function () {
    var authTokenDeffered = $.Deferred();

    if (!window.myAuthToken) {
        var authWindow = window.open(
            "https://oauth.myprovider.com/authorize?response_type=token&client_id=98599205d0aa4837a074cc19163bd38e&display=popup",
            "_blank", "modal=yes,alwaysRaised=yes");

        var checkConnect = setInterval(function () {
            if (!authWindow || !authWindow.closed) return;
            clearInterval(checkConnect);

            // I expect token here, but I do not get it
            console.log(window.myAuthToken); 

            authTokenDeffered.resolve(window.myAuthToken);
        }, 100);
    } else {
        authTokenDeffered.resolve(window.myAuthToken)
    }

    var campaigns = this.campaigns;
    return authTokenDeffered.then(function (authToken) {
        http.get('https://myprovider.com/my-service', {}, {'Authorization': 'Bearer ' + authToken})
            .then(function (response) { campaigns(response); });
    });
},

OAuth 2 回调页面有以下脚本:

var token = /access_token=([0-9a-f]+)/.exec(document.location.hash)[1];
window.parent.myAuthToken = token;
window.close();

向父级传递数据的正确方法是

window.opener.myAuthToken = token;