OAuth2和Node.js - Google确认后无重定向

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

我正在使用Node.js通过Google+验证我的网络应用程序。我按照官方指示here。我的代码看起来像这样:

var google = require('googleapis');

// OAuth
var OAuth2 = google.auth.OAuth2;
var plus = google.plus('v1');
var oauth2Client = new OAuth2(
    'MY_CLIENT_ID', // Client id
    'MY_CLIENT_SECRET', // Client secret
    'http://localhost:8080/oauth' // Redirect url
);

function getOAuthUrl(){
    var url = oauth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: 'https://www.googleapis.com/auth/plus.me'
    });

    return url;
}

// OAuth authorization
app.use('/oauth', function(req, res){
    var session = req.session;
    var code = req.query.code;

    oauth2Client.getToken(code, function(err, tokens) {
        // Now tokens contains an access_token and an optional refresh_token. Save them.
        if (!err) {
            oauth2Client.setCredentials(tokens);
            session['tokens'] = tokens;
            res.redirect(__dirname + '/public/html/redirect.html?r=1'); // Success!
        }else{
            res.redirect(__dirname + '/public/html/redirect.html?r=0'); // Fail!
        }
    });
});

登录页面在我的文件夹的根目录中被称为index.html。登录页面向/oauth/url发出ajax请求,该请求以用户必须单击的OAuth2网址进行响应。

关于index.html的JS:

/* OAuth */
$.ajax({
    url: '/oauth/url',
    dataType: 'text',
    cache: false,
    success: function (e) {
        $('#login').attr('href', e);
    }
});

Node.js响应:

// Get OAuth URL
app.use('/oauth/url', function(req, res){
    var url = getOAuthUrl();
    res.end(url);
});

我可以点击链接将我带到正常的身份验证页面。但是,当我选择要进行身份验证的帐户时,该页面会冻结,并且不会像它应该的那样重定向到localhost:8080/oauth

更新:查看控制台上的网络选项卡,我注意到正在取消对回调的GET请求。代码由Node.js接收,请求也是如此。

The console network log

node.js oauth-2.0 google-authentication
1个回答
0
投票

解决了:

问题在于静态目录不允许Node.js重定向页面。通过将重定向地址更改为/html/redirect.html来修复。谢谢你@James

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