无法访问授权cookie

问题描述 投票:0回答:1

我正在尝试为我的前端(react)实现后端(express+node +supabase)身份验证

/*BACKEND*/
//auth.js
import { supabase } from "../config/supabaseConfig.js";

export const checkMyAuthStatus = async (token) => {
  try {
    const { data, error } = await supabase.auth.getUser(token);
    if (error) {
      console.error("Failed to authenticate token:", error.message);
      return false;
    }
    return !!data.user;
  } catch (error) {
    console.error("Error checking authentication status:", error);
    return false;
  }
};
export const mySignInFunc = async (email, pass, token) => {
  try {
    const { data, error } = await supabase.auth.signInWithPassword({
      email: email,
      password: pass,
      options: {
        captchaToken: token,
      },
    });
    if (!error) {
      return { data };
    } else {
      return { error };
    }
  } catch (error) {
    console.log(error);
    return { error: "Internal server error" };
  }
};
//authRoutes.js
authRouter.get("/authStatus", async (req, res, next) => {
  const token = req.cookies.access_token;
  console.log("Cookies:", req.cookies); // Debug log

  if (!token) {
    return res.status(400).json({ error: "Authorization token is required" });
  }

  try {
    const isAuthenticated = await checkMyAuthStatus(token);
    if (isAuthenticated) {
      res.status(200).json({ message: "User is authenticated" });
    } else {
      res.status(401).json({ message: "User is not authenticated" });
    }
  } catch (err) {
    res.status(500).json({ error: "Server error" });
    console.error(err);
  }
});

此处 req.cookies 显示一个空对象,并且错误 req._implicitHeader 弹出为错误

authRouter.post("/signIn", async (req, res, next) => {
  const { mail, pass, tok } = req.body;
  const result = await mySignInFunc(mail, pass, tok);
  const sess = await result.data.session;
  if (result.error) {
    res.status(400).json({ error: result.error });
  } else {
    // res.status(200).json({ data: result.data });
    res.cookie("access_token", sess.access_token, {
      httpOnly: true, // Ensures the cookie is only accessible via HTTP(S), not JavaScript
      secure: true, // Ensures the cookie is only sent over HTTPS
      maxAge: sess.expires_in * 1000, // Sets the cookie expiration time
      sameSite: "strict",
      signed: true,
      partitioned: true,
    });
    res.status(200).json({ data: result.data });
  }
});

/signIn cookie response

//Frontend auth.ts
const isAuthenticated = async () => {
    try {
        const response = await axios.get(
            `${String(import.meta.env.VITE_BASE_URL)}/auth/authStatus`,
            {
                withCredentials: true,
            }
        );
        console.log("response", response.data);
        return response.data ? true : false;
    } catch (error) {
        console.log(error);
        return false;
    }
};

export const checkAuthStatus = async () => {
    try {
        const isAuthenticateds = await isAuthenticated();
        console.log("user is auth:", isAuthenticateds);
        return isAuthenticateds;
    } catch (error) {
        console.log(error);
        return false;
    }
};
export const signInWithEmail = async (
    mail: string,
    pass: string,
    tok: string,
    router: any
) => {
    try {
        const response = await axios.post(
            `${String(import.meta.env["VITE_BASE_URL"])}/auth/signIn`,
            { mail, pass, tok }
        );
        console.log(response.data);

        if (response.data && response.data.data && response.data.data.session) {
            // Navigate to the user home page
            router.navigate({ to: "/user/Home" });
        } else {
            console.error("Invalid response structure:", response.data);
        }
    } catch (error) {
        console.log(error);
    }
};
  1. 当我单击登录按钮时,它可以正常工作,nw 请求显示以下访问令牌
{
   "access_token": {
      "expires": "2024-07-01T11:44:30.000Z",
      "httpOnly": true,
      "path": "/",
      "samesite": "Strict",
      "secure": true,
      "value": "s:eyJhbGciOiJIUzI1NiIsImtpZCI6IkdNWGkrd2h1azB1QTZsQkYiLCJ0eXAiOiJKV1QifQ.eyJhdWQiOiJhdXRoZW5...   }
}

但是当我尝试在 /authStatus 请求中访问此令牌时,它失败了: enter image description here 2) 身份验证令牌已创建,但 authStatus 被控制台为 false,后端在 /authStatus 中显示以下错误: res._implicitHeader 不是函数,当我控制台 req.cookies 时,它是空的

那么如何更正代码

PS:

  1. 我也尝试创建一个简单的 cookie,没有 http、secure 等属性: res.cookie("access", sess.access_token) 它仍然给出相同的响应 2)corsOptions也已设置为转发凭据
const corsOptions = {
  origin: "http://localhost:5173",
  credentials: true, //access-control-allow-credentials:true
  optionSuccessStatus: 200,
};
app.use(cors(corsOptions));
javascript reactjs node.js express supabase
1个回答
0
投票

下面语句中缺少 withCredentials: true 是失败的原因。在这种情况下,服务器将创建一个 cookie 并将其发送到客户端,您可以在响应中看到该 cookie。然而,相同的 cookie 不会存储在浏览器中,因此后续对服务器的请求将无法包含它。请在声明中包含 withCredentials: true 并重试。

  const response = await axios.post(
            `${String(import.meta.env["VITE_BASE_URL"])}/auth/signIn`,
            { mail, pass, tok }
        );
© www.soinside.com 2019 - 2024. All rights reserved.