如何使用“使用服务器”来使用cookie认证

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

我正在使用 Next.js 并使用 JWT 令牌进行身份验证。登录后,我在cookies中设置了令牌。它在本地主机上完美运行,但在服务器上部署后,它无法按预期运行。使用“使用客户端”时,它在域上工作正常,但使用“使用服务器”时则不行。

有什么建议吗?

有没有像cors一样的后端实现?

我正在与虚拟 api url 共享代码

本地存储中的工作代码

"use server";

import { cookies } from "next/headers";
import Details from "../Account-Closure/details";

const fetchDummyDataWithToken = async () => {
  try {
    const cookieStore = cookies(); // Direct call without await
    const token = (await cookieStore).get("token")?.value;

    if (!token) {
      throw new Error("Token not found in cookies");
    }

    const response = await fetch(
      "https://api.co.in",
      {
        method: "GET",
        headers: {
          Authorization: Bearer ${token}, 
          "Content-Type": "application/json", // Optional: add content type
        },
      }
    );

    if (!response.ok) {
      throw new Error(Failed to fetch data. Status: ${response.status});
    }

    return response.json();
  } catch (error) {
    console.error("Error fetching data:", error);
    return null;
  }
};

const DummyApiPage = async () => {
  const apiResponse = await fetchDummyDataWithToken();

  if (!apiResponse) {
    return <div>Error fetching data. Please try again later.</div>;
  }
  console.log(apiResponse);
  const { result, data } = apiResponse;
  const { basic_details, dp_details } = data;

  return (
    <div style={{ padding: "20px", fontFamily: "Arial" }}>
      <h1>API Response</h1>
      <pre>{JSON.stringify(apiResponse, null, 2)}</pre>
      <section>
        <h2>Result</h2>
        <p>Flag: {result.flag}</p>
        <p>Message: {result.flag_message}</p>
      </section>
      <section>
        <h2>Basic Details</h2>
        <ul>
          <li>UCC Code: {basic_details.ucc_code}</li>
          <li>PAN: {basic_details.pan}</li>
          <li>Account Status: {basic_details.account_status}</li>
          <li>Date of Birth: {basic_details.date_of_birth}</li>
        </ul>
      </section>
      {/* DP Details Section */}
      <section>
        <h2>DP Details</h2>
        <ul>
          {dp_details.map((dp: any, index: any) => (
            <li key={index}>
              <strong>Depository:</strong> {dp.depository} <br />
              <strong>BO ID:</strong> {dp.bo_id} <br />
              <strong>Client ID:</strong> {dp.client_id} <br />
              <strong>Status:</strong> {dp.dp_status} <br />
              <strong>Primary Flag:</strong> {dp.primary_flag}
            </li>
          ))}
        </ul>
      </section>
    </div>
    // <>adasdahsdahsd</>
  );
};

export default DummyApiPage;
reactjs next.js server-side-rendering
1个回答
0
投票

这就是我在多个项目中所做的 为

server only

创建帮助文件

src\server\helper.ts

import 'server-only';
export enum COOKIES {
  JWT = 'token',
  RESEND_OTP_JWT = 'resend-otp-token',
  ACCEPT_COOKIES_POLICY = 'acceptCookies',
}
export const setSecureJwt = (tkn: string) => {
  cookies().set(COOKIES.JWT, tkn, {
    secure: true,
    httpOnly: true,
    sameSite: true,
  });
};
export const getAuthorizationHeader = () => {
  const token = cookies().get(COOKIES.JWT)?.value;
  if (!token) return false;
  return { Authorization: 'Bearer ' + token };
};

然后创建用于登录的服务器操作

src\server\actions\auth.actions.ts

// You can generate this token, or you can get it
// from your backend server in case your backend is on another
// server and then call the helper function
  setSecureJwt(jwt);

为游览创建一个数据库,您可以在其中使用

getAuthorizationHeader
助手 功能

src\server\data-lib\tour.data-lib.ts

import 'server-only';

import { Roles } from '@/enums';
import { REQUEST_METHODS } from '@/server/enums/shared';
import {
  getAuthorizationHeader,
  getNodeRequiredRequestHeaders,
  getCacheKey,
} from '@/server/helper';
import { getServerError } from '@/server/server-error';
import { APIResponse, ToursDetailsType } from '@/types';
import { createTourRequestURL } from '@/util';

export const getTourRequests = async (
  currentPage: number,
  role: Roles,
  propertyId?: string
) => {
  const url = createTourRequestURL(currentPage, role, propertyId);

  const res: Response = await fetch(url, {
    method: REQUEST_METHODS.GET,
    headers: {
      ...getNodeRequiredRequestHeaders(),
      ...getAuthorizationHeader(),
    },
    next: { tags: [getCacheKey('toursTable')] },
  });

  if (res.status === 404) {
    return {
      data: [],
      pages: 1,
      results: 0,
      totalDocs: 0,
    } as APIResponse<ToursDetailsType>;
  }
  if (!res.ok) {
    throw await getServerError(res);
  }
  return res.json() as Promise<APIResponse<ToursDetailsType>>;
};

然后在服务器组件中,您可以使用数据库中的辅助函数

import React from 'react';

import ToursTable from '@/components/ui/ToursTable';
import { Roles } from '@/enums';
import { getTourRequests } from '@/server/data-lib';

export default async function TableWrapper({
  currentPage,
}: {
  currentPage: number;
}) {
  const tourRequests = await getTourRequests(currentPage, Roles.TENANT);

  return (
    <ToursTable
      currentPage={currentPage}
      data={tourRequests.data}
      totalDocs={tourRequests.totalDocs}
    />
  );
}

© www.soinside.com 2019 - 2024. All rights reserved.