速成会话:当不使用LocalStrategy

时间:2019-05-01 18:41:31

标签: node.js passport.js express-session

我有一个应用程序,它使用express-sessionpassport-localconnect-ensure-login成功地验证了用户及其各自的会话。

当用passport-azure-ad Bearer OAuth策略替换护照的本地登录策略时,我发现以前找到用户与中间件会话的路由:

require('connect-ensure-login').ensureLoggedIn()

不再起作用-对req.isAuthenticated()的调用将返回false。

我可以看到,在Bearer OAuth策略成功后,会话cookie connect.sid仍在设置中。

我想我的问题是:passport-local是否正在做一些事情来启用passport-azure-ad不是的会话?

服务器设置:

const bearerToken = require('express-bearer-token');
const app = express();
app.set('trust proxy', 1)
const dataRouter =  express.Router();
dataRouter.use(bearerToken());
dataRouter.use(require('cookie-parser')());
dataRouter.use(bodyParser.urlencoded({ extended: false }));
dataRouter.use(bodyParser.json());
dataRouter.use(session({secret: 'fake secret', resave: false, saveUninitialized: false}));
dataRouter.use(passport.initialize());
dataRouter.use(passport.session());

路由设置:

router.post('/sign-in', passport.authenticate('oauth-bearer'), (req, res) => {
    res.json({ user: req.user.username } });
});
router.get('/check-session', require('connect-ensure-login').ensureLoggedIn(), (req, res) => {
    res.json({ user: req.user.username } });
});

护照设置:

const LocalStrategy = require('passport-local').Strategy;
const BearerStrategy = require('passport-azure-ad').BearerStrategy;

passport.use(new BearerStrategy(config.credentials, (req, token, done) => {
    let currentUser = null;
    let userToken = authenticatedUserTokens.find((user) => {
        currentUser = user;
        user.sub === token.sub;
    });

    if(!userToken) {
        console.log('No previous user token found');
        authenticatedUserTokens.push(token);
        currentUser = token.unique_name;
    }
    return done(null, currentUser, token);
});

passport.use('local-login', new LocalStrategy({
    usernameField: 'username',
    passwordField: 'password',
    passReqToCallback: true
},
function(req, username, password, done) {
    col.findOne({ 'local.username': username}, function(err, user) {
        if (err) {
            return done(err);
        }
        if (!user) {
            return done(null, false);
        }
        if (!validPassword(password, user.local.password)) {
            return done(null, false)
        }
        return done(null, user);
    });
}));

passport.serializeUser(function(req, user, done) {
    done(null, user._id.toString()); 
});

passport.deserializeUser(function(id, done) {
    const _id = new ObjectId(id);
    col.findOne({ _id: _id}, function(err, user) {
        if (err) {
            return done(err);
        }
        if (!user) {
            return done(null, false);
        }
        done(null, user);
    });
});

0 个答案:

没有答案