oauth 回调后 Passport 会话消失

Passport session disappears after oauth callback

使用 Ionic、Angular、nodejs 等制作混合应用

用户使用电子邮件和密码登录,然后想要将第 3 方身份验证添加到他们的帐户。
它们被序列化到会话中。
我们使用护照检查他们是否已获得第三方授权,如果没有,则发送给他们。
当用户返回回调 url 我们不再知道他们是谁,因为 req.session 未定义。

编辑:我一直在努力简化代码以找到问题所在。

// require everything and app.use them
// this is what I'm using for the session config
app.use(session({
    secret: 'thisIsASecret',
    resave: false,
    saveUninitialized: false,   
    cookie: {secure: true, maxAge: (4*60*60*1000)}
}));

var user = {  // simple user model for testing
    id: 1,
    username: 'username',
    password: 'password',
    oauthId: null
};

passport.serializeUser(function(user, done) {
    done(null, user.id);
});
passport.deserializeUser(function(id, done) {
    done(err, user);
});

// Local Passport
passport.use(new LocalStrategy(function(username, password, done) {
    return done(null, user);
}));
app.post('/login', passport.authenticate('local'), function(req, res) {
    console.log(req.session);  // Prints out session object with passport.user = 1
    res.end();
});

// oauth Passport
passport.use(new oauthStrategy({
    clientID: ****,
    clientSecret: ****,
    callbackURL: 'http://localhost:3000/auth/oauth/callback',
    passReqToCallback: true
}, function(req, accessToken, refreshToken, profile, done) {
    console.log(req.session);  // no passport object in session anymore
    return done(null, profile);
}));
app.get('/auth/oauth', passport.authorize('oauth'));
app.get('/auth/oauth/callback', passport.authorize('oauth'), function(req, res) {
    console.log(req.session);  // no passport object in session here either
    res.end();
});

在客户端登录后我使用这个,因为常规的 http 请求方法不起作用。

window.location.href = 'http://localhost:3000/auth/oauth';

编辑 2:Ionic 显然不允许会话。所以我发现您可以使用 state 参数发送带有返回回调的 oauth 请求的令牌,并将其用于 link 用户帐户的 oauth 详细信息。

app.get('auth/oauth/:token', function(req, res) {
    passport.authorize('oauth', {state: req.params.token});
});

唯一的问题是现在它不会重定向到第 3 方进行授权。只是超时...

解决方案是使用这样的路由,其中​​ token 用于识别用户。

app.get('auth/oauth/:token', function(req, res, next) {
    passport.authorize('oauth', {state: req.params.token})(req, res, next);
});

然后令牌在回调中可用 (req.query.state),我们可以将新详细信息添加到现有用户详细信息中。