Невозможно получить доступ к куки авторизации

Я пытаюсь реализовать внутреннюю аутентификацию (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.info(error);
    return { error: "Internal server error" };
  }
};
//authRoutes.js
authRouter.get("/authStatus", async (req, res, next) => {
  const token = req.cookies.access_token;
  console.info("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 });
  }
});

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

export const checkAuthStatus = async () => {
    try {
        const isAuthenticateds = await isAuthenticated();
        console.info("user is auth:", isAuthenticateds);
        return isAuthenticateds;
    } catch (error) {
        console.info(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.info(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.info(error);
    }
};
  1. когда я нажимаю кнопку входа, она работает правильно, запрос nw показывает следующий токен доступа
{
   "access_token": {
      "expires": "2024-07-01T11:44:30.000Z",
      "httpOnly": true,
      "path": "/",
      "samesite": "Strict",
      "secure": true,
      "value": "s:eyJhbGciOiJIUzI1NiIsImtpZCI6IkdNWGkrd2h1azB1QTZsQkYiLCJ0eXAiOiJKV1QifQ.eyJhdWQiOiJhdXRoZW5...   }
}

Но когда я пытаюсь получить доступ к этому токену в моем запросе /authStatus, он терпит неудачу: 2) токен аутентификации создается, но authStatus отображается как false, а серверная часть показывает следующую ошибку в /authStatus: res._implicitHeader не является функцией, и когда я консолью req.cookies, он пуст.

так как исправить код

ПС:

  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 позволяет создавать динамические и интерактивные веб-приложения.


65
1

Ответ:

Решено

Отсутствие withCredentials: true в приведенном ниже утверждении является причиной сбоя. В этом случае файл cookie будет создан и отправлен сервером клиенту, который вы можете увидеть в ответе. Однако тот же файл cookie не будет храниться в браузере, поэтому последующий запрос на сервер не сможет его включить. Пожалуйста, включите withCredentials: true в оператор и повторите попытку.

  const response = await axios.post(
            `${String(import.meta.env["VITE_BASE_URL"])}/auth/signIn`,
            { mail, pass, tok }
        );

Цитата:

Я не могу установить файлы cookie, полученные из ответа

Файлы cookie не сохраняются в браузере