簡體   English   中英

Passport和Node.JS結構

[英]Passport and Node.JS Structure

我正在使用MEAN堆棧,並希望將Passport集成到其中。 但是,我不確定要如何組織它。 我最終希望包括幾個策略,但讓我們從Google開始。

在我的routes.js文件中,我有:

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

app.get('/auth/google/return', passport.authenticate('google', { successRedirect: '/',
                                failureRedirect: '/login' }));

那講得通。 但是,我應該在頂層server.js中將GoogleStrategy()構造函數/成功回調代碼放在哪里? 假設我有5種不同的策略,它們都應該加入其中嗎?

對於我們的應用,我們創建了一個單獨的passport.js文件,其中包含我們所有的社交注冊策略以及一個單獨的路由文件,這就是我們的Google外觀:

app.js

var social  = require('./routes/social.js')
..

app.get('/auth/google', passport.authenticate('google'));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/signup', failureFlash: true}), social.googleCallback);

passport.js (位於根目錄中)

var passport = require('passport'),
    GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
    config = require('./config');
var socialAuth = config.socialAuth; //contains keys

module.exports = function(passport) {
    /*DEFINE LOGIN STRATS HERE*/
    //GOOGLE+
    passport.use(new GoogleStrategy({
        clientID: socialAuth.google.GOOGLE_CLIENT_ID,
        clientSecret: socialAuth.google.GOOGLE_CLIENT_SECRET,
        callbackURL: config.callbackDomain + "/auth/google/callback",
        scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
    }, function(accessToken, refreshToken, profile, done) {
            //code for strat here
            return done(null, userDoc);
       }
    });
}

social.js (路由)

exports.googleCallback = function(req, res) {
    //do stuff with the return from passport
}

它非常適合管理所需的每種策略,並且很容易添加。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM