Set-Cookie来自服务器的响应,但未存储在存储cookie中

时间:2020-01-02 17:57:46

标签: reactjs cookies graphql setcookie

我的Graphql服务器有问题,并做出了反应。

提交“登录”突变时,将正确处理该突变并接收数据。 响应标头中接收到“ Set-Cookie”,但未将其存储在浏览器cookie中。
我已经尝试过其他关于堆栈溢出的其他讨论中提出的解决方案,但是都没有用。

enter image description here

enter image description here

这是我的后端代码:

index.js

    const express = require("express");
    const mongoose = require("mongoose");
    const { ApolloServer, AuthenticationError } = require("apollo-server-express");
    const cors = require("cors");
    const cookieParser = require("cookie-parser");
    const jwt = require("jsonwebtoken");
    const resolvers = require("./graphql/resolvers");
    const typeDefs = require("./graphql/typeDefs");
    require("dotenv").config();

    const users = [
      {
        id: 1,
        name: "Test user",
        email: "your@email.com",
        password: "$2b$10$ahs7h0hNH8ffAVg6PwgovO3AVzn1izNFHn.su9gcJnUWUzb2Rcb2W" // = ssseeeecrreeet
      }
    ];

    mongoose
      .connect(process.env.MONGO_URI, {
        useNewUrlParser: true,
        useUnifiedTopology: true
      })
      .then(() => console.log("DB Connected"))
      .catch(err => console.error(err));

    const corsOptions = {
      credentials: true,
      origin: "http://localhost:3000"
    };
    const app = express();
    const port = 4000;
    app.use(cors(corsOptions));
    app.use(cookieParser());
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));

    const context = async request => {
      let authToken = null;
      let currentUser = null;
      const { headers } = request.req;
      try {
        authToken = headers.authorization || "";
        if (authToken) {
          currentUser = jwt.verify(authToken, process.env.SECRET_KEY);
        }
      } catch (error) {
        throw new AuthenticationError(
          "Authentication token is invalid, please log in"
        );
      }
      return { request, currentUser };
    };

    const server = new ApolloServer({
      typeDefs,
      resolvers,
      context
    });

    server.applyMiddleware({ app, path: "/graphql" });

    app.listen(port, () => console.log(`Server started: http://localhost:${port}`));

resolvers.js

module.exports = {
  Mutation: {
    signin: async (root, args, ctx) => {
      console.log(ctx.currentUser);
      // Make email lowercase
      const email = args.email.toLowerCase();
      // Check if User exists
      const userExist = await User.findOne({ email });
      if (!userExist) {
        throw new Error("User does not exist, please signup for new account");
      }
      // Check if passwords match
      const match = await bcrypt.compare(args.password, userExist.password);
      if (!match) {
        throw new Error("Invalid username or Password");
      }
      // Create a token and assign
      const token = jwt.sign(
        { email: userExist.email, id: userExist._id },
        process.env.SECRET_KEY,
        { expiresIn: "1day" }
      );
      // Assign to cookie
      ctx.request.res.cookie("token", token, {
        httpOnly: true,
        maxAge: 60 * 60 // 1 Hour
        // secure: true, //on HTTPS
        // domain: 'example.com', //set your domain
      });
      return userExist;
    }
  }
};

然后在客户端(反应)端:

import React, { useContext, useReducer } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

import App from "./App";
import Splash from "./pages/Splash";
import Context from "./context";
import reducer from "./reducer";
import ProtectedRoute from "./ProtectedRoute";

import * as serviceWorker from "./serviceWorker";

import { ApolloProvider } from "react-apollo";
import { ApolloClient } from "apollo-client";
import { createHttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";

const client = new ApolloClient({
  link: createHttpLink({
    uri: "http://localhost:4000/graphql",
    credentials: "include"
  }),
  cache: new InMemoryCache()
});

const Root = () => {
  const initialState = useContext(Context);
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <Router>
      <ApolloProvider client={client}>
        <Context.Provider value={{ state, dispatch }}>
          <Switch>
            <ProtectedRoute exact path="/" component={App} />
            <Route path="/login" component={Splash} />
          </Switch>
        </Context.Provider>
      </ApolloProvider>
    </Router>
  );
};

ReactDOM.render(<Root />, document.getElementById("root"));

Login.js组件

// Imports Omitted

export default function SignIn() {

const onSubmit = async ({ email, password }) => {
    const variables = { email, password };
    const client = new GraphQLClient(BASE_URL);
    const data = await client.request(SIGNIN_MUTATION, variables);
    console.log(data);
  };


// return info omitted

4 个答案:

答案 0 :(得分:2)

在您的resolver.js中将SameSite:None更改为SameSite:Lax

ctx.request.res.cookie("token", token, {
     httpOnly: true,
     maxAge: 60 * 60 // 1 Hour
     // secure: true, //on HTTPS
     // domain: 'example.com', //set your domain
     sameSite: 'lax',
    }

参考:

https://web.dev/samesite-cookies-explained/#explicitly-state-cookie-usage-with-the-samesite-attribute

https://github.com/GoogleChromeLabs/samesite-examples/blob/master/javascript-nodejs.md

答案 1 :(得分:0)

在响应标头中包含标头并不意味着您可以使用它们 无论是api还是网络服务器,都应将set-cookie放在Access-Control-Allow-Headers中,以使浏览器使用给定的cookie

答案 2 :(得分:0)

这个配置对我有用。

这个cookie的配置

cookie: {
    path: '/',
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: true,
    maxAge: 60000, //time exp
    domain: 'localhost' //or other domain
  }

CORS / nodeJs 的配置

configCors = {
  origin: [`http://${process.env.SERVER_NAME}`, 'http://localhost:3000'],
  credentials: true
}

最后,作为“包括”阿波罗凭证 我遇到了同样的问题,但我用 graphql 凭证(阿波罗)解决了它

答案 3 :(得分:0)

[编辑]: 缺少的路径和“Access-Control-Allow-Headers”-“Origin、X-Requested-With、Content-Type、Accept”多次导致 Chrome(或更新的浏览器)出现问题。可以 HttpOnly 和 SameSite=Strict,但不要忘记添加缺少的属性。

补充说明: 它可能是由安全机制引起的:

选项 A.) - 代理方式

1.) 确保在前端的 package.json 中使用代理与后端的相同端点。

喜欢:

"proxy": "http://localhost:8080/api/auth" 

如果您在 :8080 上运行后端。

2.) 在您的服务文件(或您想调用后端的任何地方)中,相对路径就足够了,因此您无需指定整个路径,这要归功于代理服务器 url。

喜欢:

...

  return axios
    .post("/signin", {
      username,
      password,
    })

...

关于同源策略的更多信息: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

选项 B.) - CORS 方式

对于 Spring 用户:除了提到的标头设置之外,不要忘记将 @CrossOrigin origins 和 allowCredentials 设置为 true。 喜欢:

@CrossOrigin(origins = {"http://127.0.0.1:8089", "http://localhost:3001"}, allowCredentials = "true")

希望对某人有所帮助。 快乐黑客!