是否可以在不设置重定向URI的情况下获取Google Ouath2访问令牌?

问题描述 投票:1回答:1

我正在尝试在弹出窗口中实现Google Oauth2同意屏幕,但显示重定向URI不匹配。有什么方法可以设置Web Ouath Client App,而无需在仪表板上设置重定向uri?

我知道从网络向其他人或应用程序设置客户端类型可以解决此问题。但是我只想针对Web类型实现它。这可能吗?

<!DOCTYPE html>
<html>
<head>

<script>
'use strict';

var GO2 = function GO2(options) {
    if (!options || !options.clientId) {
        throw 'You need to at least set the clientId';
    }

    if (typeof window != 'undefined'){
        this._redirectUri = window.location.href.substr(0,
            window.location.href.length -
            window.location.hash.length)
            .replace(/#$/, '');
    }


    // Save the client id
    this._clientId = options.clientId;

    // if scope is an array, convert it into a string.
    if (options.scope) {
        this._scope = Array.isArray(options.scope) ?
            options.scope.join(' ') :
            options.scope;
    }

    // rewrite redirect_uri
    if (options.redirectUri) {
        this._redirectUri = options.redirectUri;
    }

    // popup dimensions
    if (options.popupHeight) {
        this._popupHeight = options.popupHeight;
    }
    if (options.popupWidth) {
        this._popupWidth = options.popupWidth;
    }

    if (options.responseType) {
        this._responseType = options.responseType;
    }

    if (options.accessType) {
        this._accessType = options.accessType;
    }
};

GO2.receiveMessage = function GO2_receiveMessage() {
    var go2;
    if (window.opener && window.opener.__windowPendingGO2) {
        go2 = window.opener.__windowPendingGO2;
    }
    if (window.parent && window.parent.__windowPendingGO2) {
        go2 = window.parent.__windowPendingGO2;
    }

    var hash = window.location.hash;
    if (go2 && hash.indexOf('access_token') !== -1) {
        go2._handleMessage(
            hash.replace(/^.*access_token=([^&]+).*$/, '$1'),
            parseInt(hash.replace(/^.*expires_in=([^&]+).*$/, '$1'), 10),
            hash.replace(/^.*state=go2_([^&]+).*$/, '$1')
        );
    }

    if (go2 && window.location.search.indexOf('code=')) {
        go2._handleMessage(
            window.location.search.replace(/^.*code=([^&]+).*$/, '$1'),
            null,
            window.location.search.replace(/^.*state=go2_([^&]+).*$/, '$1')
        );
    }

    if (go2 && window.location.search.indexOf('error=')) {
        go2._handleMessage(false);
    }
};

GO2.prototype = {
    WINDOW_NAME: 'google_oauth2_login_popup',
    OAUTH_URL: 'https://accounts.google.com/o/oauth2/v2/auth',

    _clientId: undefined,
    _scope: 'https://www.googleapis.com/auth/plus.me',
    _redirectUri: '',

    _popupWindow: null,
    _immediateFrame: null,

    _stateId: Math.random().toString(32).substr(2),
    _accessToken: undefined,
    _timer: undefined,

    _popupWidth: 500,
    _popupHeight: 400,

    _responseType: 'token',
    _accessType: 'online',

    onlogin: null,
    onlogout: null,


    login: function go2_login(forceApprovalPrompt, immediate) {
        if (this._accessToken) {
            return;
        }

        this._removePendingWindows();

        window.__windowPendingGO2 = this;

        var url = this.OAUTH_URL +
            '?response_type=' + this._responseType +
            '&access_type='+ encodeURIComponent(this._accessType) +
            '&redirect_uri=' + encodeURIComponent(this._redirectUri) +
            '&scope=' + encodeURIComponent(this._scope) +
            '&state=go2_' + this._stateId +
            '&client_id=' + encodeURIComponent(this._clientId);

        console.log(url);

        if (!immediate && forceApprovalPrompt) {
            url += '&approval_prompt=force';
        }

        if (immediate) {
            url += '&approval_prompt=auto';

            // Open up an iframe to login
            // We might not be able to hear any of the callback
            // because of X-Frame-Options.
            var immediateFrame =
                this._immediateFrame = document.createElement('iframe');
            immediateFrame.src = url;
            immediateFrame.hidden = true;
            immediateFrame.width = immediateFrame.height = 1;
            immediateFrame.name = this.WINDOW_NAME;
            document.body.appendChild(immediateFrame);

            return;
        }

        // Open the popup
        var left =
            window.screenX + (window.outerWidth / 2) - (this._popupWidth / 2);
        var top =
            window.screenY + (window.outerHeight / 2) - (this._popupHeight / 2);
        var windowFeatures = 'width=' + this._popupWidth +
            ',height=' + this._popupHeight +
            ',top=' + top +
            ',left=' + left +
            ',location=no,toolbar=no,menubar=no';
        this._popupWindow = window.open(url, this.WINDOW_NAME, windowFeatures);
    },

    logout: function go2_logout() {
        if (!this._accessToken) {
            return;
        }

        this._removePendingWindows();

        clearTimeout(this._timer);
        this._accessToken = undefined;
        if (this.onlogout) {
            this.onlogout();
        }
    },

    getAccessToken: function go2_getAccessToken() {
        return this._accessToken;
    },

    // receive token from popup / frame
    _handleMessage: function go2_handleMessage(token, expiresIn, stateId) {
        if (this._stateId !== stateId) {
            return;
        }

        this._removePendingWindows();

        // Do nothing if there is no token received.
        if (!token) {
            return;
        }

        this._accessToken = token;

        if (this.onlogin) {
            this.onlogin(this._accessToken);
        }

        if (expiresIn) {
            // Remove the token if timed out.
            clearTimeout(this._timer);
            this._timer = setTimeout(
                function tokenTimeout() {
                    this._accessToken = undefined;
                    if (this.onlogout) {
                        this.onlogout();
                    }
                }.bind(this),
                expiresIn * 1000
            );
        }
    },

    destory: function go2_destory() {
        if (this._timer) {
            clearTimeout(this._timer);
        }
        this._removePendingWindows();
    },

    _removePendingWindows: function go2_removePendingWindows() {
        if (this._immediateFrame) {
            document.body.removeChild(this._immediateFrame);
            this._immediateFrame = null;
        }

        if (this._popupWindow) {
            this._popupWindow.close();
            this._popupWindow = null;
        }

        if (window.__windowPendingGO2 === this) {
            delete window.__windowPendingGO2;
        }
    }
};

// if the context is the browser
if (typeof window !== 'undefined') {
    // If the script loads in a popup matches the WINDOW_NAME,
    // we need to handle the request instead.
    if (window.name === GO2.prototype.WINDOW_NAME) {
      GO2.receiveMessage();
    }
}

// Expose the library as an AMD module
if (typeof define === 'function' && define.amd) {
    define('google-oauth2-web-client', [], function () { return GO2; });
} else if (typeof module === 'object' && typeof require === 'function') {
    // export GO2 in Node.js, assuming we are being browserify'd.
    module.exports = GO2;

    if (require.main === module) {
        console.error('Error: GO2 is not meant to be executed directly.');
    }
} else {
    window.GO2 = GO2;
}

function test(){
    var go2 = new GO2({
        clientId: 'dfsdffdfgsfsdfggdgd.apps.googleusercontent.com',
        redirectUri: 'http://localhost:8888/gapi/test.html',
        responseType: 'code',
        accessType: 'offline'
    });

    go2.login();    
}


    </script>


</head>

<body>
    <a href='#' onClick='test();'> Click here to login </a>
</body>
</html>
oauth-2.0 google-oauth2
1个回答
0
投票

似乎您使用的是隐式授予类型,该类型要求使用带有response_type = token的重定向uri。

您可以使用授权码授予类型吗?

重定向uri对于授权码授予类型是可选的。

https://tools.ietf.org/html/rfc6749#section-4.1.1

© www.soinside.com 2019 - 2024. All rights reserved.