Apollo Express没有快速护照会议

时间:2019-02-15 05:48:38

标签: express graphql passport.js apollo-server

对于我们的门户网站,我将我的快递服务器与通行证集成在一起以对用户进行身份验证。用户身份验证后,需要使用客户端的相同会话从我们的api获取用户详细信息。护照身份验证可在我的门户上运行,并且能够查看用户登录的身份提供者数据。但是,当从React端执行任何GraphQL调用时,Apollo服务器在其请求中都没有用户会话,但表达了请求。

遵循此处https://www.apollographql.com/docs/apollo-server/essentials/server.html#ssl所述的步骤,但是在为ApolloServer设置上下文时,req会话中没有护照。

        const express = require('express');
        const session = require('express-session');
        const { ApolloServer } = require('apollo-server-express');
        const addResolveFunctionsToSchema = require('graphql-tools').addResolveFunctionsToSchema;
        const mongooseConnection = require('./src/persistence/mongooseConnection');
        const MongoSession = require('connect-mongo')(session);
        const config = require('config');
        const mongo = config.get('mongo');
        const fs = require('fs');
        const https = require('https');
        const bodyParser = require('body-parser');
        const cookieParser = require('cookie-parser');
        const configSession = config.get('session');
        const configPassport = config.get('passport');
        const configCommon = config.get('common');
        const resolvers = require('./src/resolvers');
        const schema = require('./src/schema');
        const uri = `${mongo.uri}/${mongo.database}`;
        const app = express();
        var passport = require('passport');
        const SamlStrategy = require('passport-saml').Strategy;
        const authRoute = require('./routes/auth');

        const apiRoute = require('./routes/userDetails');
        const Helmet = require('helmet');
        require('reflect-metadata');

        mongooseConnection.create();

        let mongoOptions = {};

        const mongoSessionStore = new MongoSession({
            url: `${uri}`,
            mongoOptions: mongoOptions,
            collection: configSession.mongo.collection
        });
        addResolveFunctionsToSchema(schema, resolvers);

        passport.use(
            new SamlStrategy(
                {
                    entryPoint: configPassport.entry_point,
                    // issuer: 'passport-saml',
                    protocol: 'https',
                    callbackURL: `${configCommon.dns}/${configPassport.callback_url}`,
                    // cert: adfsTokenSigningCert,
                    identifierFormat: null,
                    forceAuthn: true,
                    signatureAlgorithm: 'sha256',
                    acceptedClockSkewMs: -1
                },
                (profile, cb) => {
                    cb(null, profile);
                }
            )
        );

        passport.serializeUser(function(user, done) {
            done(null, userData);
        });

        passport.deserializeUser(function(obj, done) {
            done(null, obj);
        });

        app.use(cookieParser());

        app.use(
            session({
                secret: 'project',
                secret: configSession.config.secret,
                resave: false,
                saveUninitialized: false,
                store: mongoSessionStore,
                sameSite: true,
                rolling: true,
                name: 'project',
                cookie: {
                    secure: true,
                    domain: configCommon.cookie_domain
                }
            })
        );

        // Initialize Passport
        app.use(passport.initialize());
        app.use(passport.session());
        app.use(bodyParser.json());
        app.use(
            bodyParser.urlencoded({
                extended: false
            })
        );
        // setting up security headers
        app.use(Helmet());

        app.get('/s/health-check', (req, res) => {
            res.send(`I am alive!!!!`);
        });

        app.use('/s/api', apiRoute);
        app.use('/s/auth', authRoute); // API integration

        const isDev = process.env.NODE_ENV !== 'prod';

        const apolloServer = new ApolloServer({
            schema,
            resolvers,
            context: ({ req }) => {
                console.log(req) //req.session don't have passport in it
                return {
                    req
                };
            }
        });

        apolloServer.applyMiddleware({
            app,
            path: '/graphql'
        });

        apolloServer.installSubscriptionHandlers(app);

        https
            .createServer(
                {
                    key: fs.readFileSync(`./keys/server.key`),
                    cert: fs.readFileSync(`./keys/server.crt`)
                },
                app
            )
            .listen(process.env.PORT, () => {
                console.log('Express server is running on port 9091');
            });

        // Handle uncaughtException
        process.on('uncaughtException', err => {
            console.log(err.message);
            process.exit(1);
        });

1 个答案:

答案 0 :(得分:0)

再次检查请求是否正在发送会话cookie。我遇到了同样的问题,并且我使用Graphql Playground作为客户端,并且默认情况下它禁用发送cookie。您可以通过以下方法修复它:转到操场右上角的设置,然后设置"request.credentials": "same-origin"。完成后,我看到护照会话已正确初始化。