简体   繁体   English

使用Node.js和Google&Javascript进行OAuth 2登录

[英]OAuth 2 Login using Node.js and Google & Javascript

This is a follow-up from my earlier question here; 这是我之前在这里提出的问题的跟进; invalid_request from getToken in Javascript from Node.js 来自Node.js的Javascript中的getToken的invalid_request

The application first redirects to google; 该应用程序首先重定向到google;

app.get('/GoogleLogin.html',function(req,res) {
var scopes = "";

// retrieve google scopes
scopes += config.google_login.scopes.baseFeeds + " "
scopes += config.google_login.scopes.calendar + " "
scopes += config.google_login.scopes.drive + " "
scopes += config.google_login.scopes.driveMetadata + " "
scopes += config.google_login.scopes.profile + " "
scopes += config.google_login.scopes.email + " "
scopes += config.google_login.scopes.tasks

var url = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: scopes
});

res.writeHead(302, {location: url});
res.end();


});

it redirects to google to get the code, then when it returns back, it calls oauth2Client.getToken in order to convert that code to tokens. 它将重定向到google以获取代码,然后在返回时调用oauth2Client.getToken以便将该代码转换为令牌。

app.get('/AuthorizeGoogle.html',function(req,res) {
var queryData   = url.parse(req.url,true).query;
var code        = queryData.code;
var access_token = "";

oauth2Client.getToken(code,function(err,tokens) {
    if (err == null) {
        oauth2Client.setCredentials(tokens);        
        access_token = tokens.access_token;
        googleapis
            .discover('plus','v1')
            .withAuthClient(oauth2Client)
            .execute(function(err, client) {        
                if (err) {
                    console.log('An error occured');
                } 
                else {                      
                    getUserProfile(client, oauth2Client, 'me', function(err, profile) {
                        if (err) {
                            console.log('An error occured retrieving the profile');                                 
                        }
                        else {

                        }
                    });
                }

            });
    } 
    else {
        console.log("There seems to be a problem; " + err);
    }


    res.send("Authorized!");
});

That is OK as far as it goes. 就目前而言还可以。 However when I next login, using the same google account I get a different code and token. 但是,当我下次登录时,使用相同的Google帐户,我会得到不同的代码和令牌。 Although the original login and authorisation returns both a token and refresh token - subsequent attempts do not have the refresh token. 尽管原始登录名和授权都返回令牌和刷新令牌,但是后续尝试都没有刷新令牌。

As they are different there is no way of telling if the user has already logged in and we have already been authorised. 由于它们不同,因此无法判断用户是否已经登录并且我们已经被授权。

When I did the same thing in C# - I could use the token to search the database and so link it with user. 当我在C#中执行相同的操作时-我可以使用令牌搜索数据库,然后将其与用户链接。

So how can I use Google to login and find the user without in effect refreshing the token - since later I will be using the access token to get other parts of the users Google account such as Documents, Emails, Tasks etc. 因此,我该如何使用Google登录并找到用户,而实际上不刷新令牌-因为稍后我将使用访问令牌来获取用户Google帐户的其他部分,例如文档,电子邮件,任务等。

Thanks in advance 提前致谢

OK Kind of managed it. 好的,可以管理它。

Basically instead of using OAuth 2 for both logging on and authorization - I am using OpenId for the login and OAuth2 for the authorization. 基本上,而不是使用OAuth 2进行登录和授权-我使用OpenId进行登录,并使用OAuth2进行授权。

OpenId functionality is provided by both passport and passport-google. 通行证和passport-google均提供OpenId功能。

var passport        = require('passport');
var GoogleStrategy  = require('passport-google').Strategy;

app.use(passport.initialize());
app.use(passport.session()); 

You need to initialise passport 您需要初始化护照

passport.use(new GoogleStrategy({
    returnURL: 'http://localhost:81/AuthenticateGoogleLogin.html',
    realm: 'http://localhost:81/',
    clientID: config.google_login.client_id,
    clientSecret: config.google_login.client_secret,
},
function(identifier, profile, done) {
    return done(null,profile);
}));

You then get Google to log the user in 然后,您可以让Google登录该用户

app.get('/GoogleLogin.html',passport.authenticate('google', { failureRedirect: '/login' }),
    function(req, res) {
        res.redirect('/');  
});

When Google Returns, using the strategy created earlier Google回归时,使用之前创建的策略

app.get('/AuthenticateGoogleLogin.html', 
  passport.authenticate('google', { failureRedirect: '/Problem.html' }),
  function(req, res) {

});

That handles the login and the authorization to access the users account is exactly as in my original question. 处理登录和访问用户帐户的授权与我最初的问题完全相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM