node.js 本地主机上的护照谷歌 oauth

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24352975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:31:33  来源:igfitidea点击:

passport google oauth on localhost

node.jsexpressoauth-2.0passport.js

提问by frictionlesspulley

I am quite new at using passport for authentication over node, hence the lot of code snippets

我对使用通行证通过节点进行身份验证很陌生,因此有很多代码片段

my server is configured as :

我的服务器配置为:

var router = require('./app/config/routes');
var googleStrategy = require('./app/config/passport');
var session = require("express-session");

var passport = require('passport');
app.use(session({secret : '<secret-key>'}));
app.use(passport.initialize());
app.use(passport.session());
googleStrategy(passport); 

my routes are configured as

我的路线配置为

module.exports = function(app, passport) {

    app.get('/auth/google', function() {
        passport.authenticate('google', {scope: ['profile', 'email']});
    });

    app.get('/auth/google/callback', function() {
        passport.authenticate('google', {
            successRedirect: '/profile',
            failureRedirect: '/fail'
        });
    });

    .... ALSO configured /profile and /fail
};

my passport is configured as

我的护照配置为

passport.serializeUser(function(user, callback){
        console.log('serializing user.');
        callback(null, user);
    });

    passport.deserializeUser(function(user, callback){
       console.log('deserialize user.');
       callback(null, user);
    });

    var processRequest = function(token, refreshToken, profile, callback){
        process.nextTick(function(){
           console.log('id : '+ profile.id);
           console.log('name :'+ profile.displayName);
           console.log('email :' + profile.emails);
           console.log('token : '+ token);
        });
    };

    passport.use(new GoogleStrategy({
        clientID: 'client ID',
        clientSecret : 'client SECRET',
        callbackURL : 'http://127.0.0.1:8080/auth/google/callback',
        realm : 'http://127.0.0.1:8080'
    }, processRequest));

Problem : on going to /auth/google, I never get a confirmation screen. What should be I looking at?

问题:在去的时候/auth/google,我从来没有得到确认屏幕。我应该看什么?

Update :

更新 :

changing the routes to the configuration shown below made it work.

将路由更改为如下所示的配置使其工作。

    app.get('/auth/google', 
        passport.authenticate('google', {scope: ['profile', 'email']})
    );

    app.get('/auth/google/callback', 
        passport.authenticate('google', {
            successRedirect: '/profile',
            failureRedirect: '/fail'
        })
    );

回答by Karthic Rao

Currently OAUTH2 protocol for authentication and autherization is well supported by google.So Its better to use the same . Here isgoogle's documentation on it .Use 'passport-google-oauth'module . Here is the implementation.This should be the app objects configuration , also see that oauth2strategy object is used from passport-google-oauth module , also check out the scopes in the app.get route registration .

目前谷歌很好地支持用于身份验证和授权的 OAUTH2 协议。所以最好使用相同的 . 这是谷歌的文档。使用“passport-google-oauth”模块。这是实现。这应该是应用程序对象配置,还可以看到从passport-google-oauth 模块中使用的oauth2strategy 对象,还可以查看app.get 路由注册中的范围。

var googleStrategy = require('passport-google-oauth').OAuth2Strategy;
  app.configure(function() {

    app.set('views',  './views');
    app.set('view engine', 'jade');
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use(express.session({secret:'MySecret'}));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static('./public'));
});

app.get('/auth/google', select.passport.authenticate('google',{scope: 'https://www.googleapis.com/auth/plus.me https://www.google.com/m8/feeds https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile'}));

app.get('/auth/google/callback', function() {
    passport.authenticate('google', {
        successRedirect: '/profile',
        failureRedirect: '/fail'
    });
});
app.get('/logout', function (req, res) {
        req.logOut();
        res.redirect('/');
    });

But before creating a new strategy go to googles developer console and get clientID and secret . Here are the steps

但是在创建新策略之前,请转到 googles 开发人员控制台并获取 clientID 和 secret 。以下是步骤

  1. go this linkand create project , here is the snapshot of the same enter image description here
  2. give a new project name and ID , here is the snapshot enter image description here
  3. It'll roughly take a minute to create your new project , once your new project is created it'll redirect you to the application configuration of your app . In the redirected page select APIS AND AUTH-> API's, In the API's page enable the GOogle+ API , here is the snapshot of it enter image description here
  4. then go to credentials(below APIs), then click on Create New Client Id, and register the domains and callback for your app(configure the domain to be localhost ) , here is its snapshot !enter image description here5.Then u'll get your new ID and secret . Use them to create the new Strategy

    passport.use(new googleStrategy({
        clientID: '<TheNewclientID>',
        clientSecret: '<The New Secret>',
    
        callbackURL: "http://locahost:8080/auth/google/callback"
    },
    function (accessToken, refreshToken, profile, done) {
        console.log(profile); //profile contains all the personal data returned 
        done(null, profile)
    }
    ));
    
  1. 转到此链接并创建项目,这是相同的快照在此处输入图片说明
  2. 给出一个新的项目名称和 ID,这是快照 在此处输入图片说明
  3. 创建新项目大约需要一分钟,一旦创建新项目,它会将您重定向到应用程序的应用程序配置。在重定向页面中选择APIS AND AUTH-> API's,在 API 页面中启用 GOogle+ API ,这是它的快照在此处输入图片说明
  4. 然后转到凭据(在 API 下方),然后单击“创建新客户端 ID”,并为您的应用注册域和回调(将域配置为 localhost ),这是它的快照!在此处输入图片说明5.然后你会得到你的新ID和秘密。使用它们来创建新的策略

    passport.use(new googleStrategy({
        clientID: '<TheNewclientID>',
        clientSecret: '<The New Secret>',
    
        callbackURL: "http://locahost:8080/auth/google/callback"
    },
    function (accessToken, refreshToken, profile, done) {
        console.log(profile); //profile contains all the personal data returned 
        done(null, profile)
    }
    ));
    

6.now serialize and deserialize

6.now序列化和反序列化

passport.serializeUser(function(user, callback){
        console.log('serializing user.');
        callback(null, user.id);
    });

passport.deserializeUser(function(user, callback){
       console.log('deserialize user.');
       callback(null, user.id);
    });

run the server and go to localhost:8080/auth/google (dont use 127.0.0.1:8080 instead of locahost ) .This should be getting it working :)

运行服务器并转到 localhost:8080/auth/google(不要使用 127.0.0.1:8080 而不是 locahost )。这应该让它工作:)

[Other useful links: Check out the first comment by kvcrawford on the repo of the module in thispage Passport-google is another popular module which is use to provide login using google , its kind of outdated now , here is the linkwith respect to its recent issues ]

[其他有用的链接:由kvcrawford在模块的回购退房的第一个评论页护照,谷歌是另一种流行的模块,它是利用提供登录使用谷歌,它的种类现在已经过时,这里是链接相对于其最近的问题]

回答by Seiya Mizuno

In most examples on the web, routing code is done like this:

在网络上的大多数示例中,路由代码是这样完成的:

app.get('/auth/google', passport.authenticate('google'));

According to the Express Reference, callbacks of the app.getmethod are given three arguments, request, responseand 'next'. That means, the authenticate method in the above example returns a function object and it is executed with three the arguments request, responseand 'next'.

根据Express Reference,该app.get方法的回调被赋予三个参数requestresponse和 'next'。这意味着,在上述例子中的authenticate方法返回一个功能对象,并将其与三个参数执行requestresponse和“下一步”。

So, if you would like do authentication in the callback function of the app.getmethod like this:

因此,如果您想在方法的回调函数中进行身份验证,app.get如下所示:

app.get('/auth/google', function() {
    passport.authenticate('google', {scope: ['profile', 'email']});
});

then you should write:

那么你应该写:

app.get('/auth/google', function(request, response, next) {
    passport.authenticate('google', {scope: ['profile', 'email']})(request, response, next);
});

回答by rust

I agree with you @Seiya but I would add a redirect

我同意你@Seiya,但我会添加一个重定向

app.get(
    "/auth/google/callback", 
    passport.authenticate('google'),
    (req, res) => {
      res.redirect('/whatever')
    }
);