会话Cookie不在浏览器上保存

时间:2018-06-10 13:24:23

标签: express graphql express-session

我正在使用此回购中的代码: prisma-cookies

一切似乎都有效,但是当我使用graphql playground测试服务器时,会话cookie没有保存在我的浏览器上。换句话说,我向服务器发送登录变异,登录明显有效,但浏览器上没有保存cookie。

我正在NodeJS上的ExpressJS上运行GraphQL瑜伽服务器。

如果您需要我添加任何其他信息,请与我们联系。
非常感谢您的帮助!

index.ts

import { GraphQLServer } from "graphql-yoga";
import * as session from "express-session";
import { Prisma } from "./generated/prisma";
import resolvers from "./resolvers";

const server = new GraphQLServer({
  typeDefs: "./src/schema.graphql",
  resolvers,
  context: req => ({
    ...req,
    db: new Prisma({
      endpoint: process.env.PRISMA_ENDPOINT, // the endpoint of the Prisma DB service (value is set in .env)
      secret: process.env.PRISMA_SECRET, // taken from database/prisma.yml (value is set in .env)
      debug: true // log all GraphQL queries & mutations
    })
  })
});

const SESSION_SECRET = "lsdfjlkjlkewaqra";

server.express.use(
  session({
    name: "qid",
    secret: SESSION_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      maxAge: 1000 * 60 * 60 * 24 * 7 // 7 days
    }
  })
);

const cors = {
  credentials: true,
  origin: "http://localhost:3000"
};

server.start({ cors }, () =>
  console.log(`Server is running on http://localhost:4000`)
);

auth.ts

import * as bcrypt from "bcryptjs";
import * as jwt from "jsonwebtoken";
import { Context } from "../../utils";

export const auth = {
  async signup(parent, args, ctx: Context, info) {
    const password = await bcrypt.hash(args.password, 10);
    const user = await ctx.db.mutation.createUser({
      data: { ...args, password }
    });

    ctx.request.session.userId = user.id;

    return {
      user
    };
  },

  async login(parent, { email, password }, ctx: Context, info) {
    const user = await ctx.db.query.user({ where: { email } });
    if (!user) {
      throw new Error(`No such user found for email: ${email}`);
    }

    const valid = await bcrypt.compare(password, user.password);
    if (!valid) {
      throw new Error("Invalid password");
    }

    ctx.request.session.userId = user.id;

    return {
      user
    };
  }
};

util.ts

import * as jwt from "jsonwebtoken";
import { Prisma } from "./generated/prisma";

export interface Context {
  db: Prisma;
  request: any;
}

export function getUserId(ctx: Context) {
  if (ctx.request.session.userId) {
    return ctx.request.session.userId;
  }

  throw new AuthError();
}

export class AuthError extends Error {
  constructor() {
    super("Not authorized");
  }
}

1 个答案:

答案 0 :(得分:0)

因此,graphql操场上目前确实存在一个错误。在过去的两天里,我花了大约12个小时来试图弄清问题所在。问题是Graphql Playground没有随您的请求一起发送凭据。从理论上讲,您应该可以单击右上角的设置图标,并将“凭据”更改为“包含”,但它们仍将以“忽略”的形式发送。

https://github.com/prisma/graphql-playground/issues/826