【问题标题】:How could i pass cookies in Axios我如何在 Axios 中传递 cookie
【发布时间】:2022-01-13 02:41:49
【问题描述】:

我在 next-js 应用程序中,我的身份验证令牌存储在 cookie 中。 对于某些原因,我使用 Swr 和 Api 路由来获取我的安全 api 后端。 我正在尝试找到一种方法将我的身份验证令牌放入所有 api 请求中。

在设置登录 cookie 期间

  res.setHeader(
        'Set-Cookie',
        cookie.serialize('token', data.access_token, {
          httpOnly: true,
          secure: process.env.NODE_ENV !== 'development',
          maxAge: data.expires_in, // 1 week
          sameSite: 'strict',
          path: '/',
        }),
      );

这是一个使用 swr fetch 的页面示例

//page/test.ts - example of my test route

  const { data, error } = useFetchContent(id);

  if (error) {
    showError('error');
    replace('/');
  }

  return <DisplayContent content={data} />

这是一个 swrFetchHook

// fetchContentHook 

function useFetchContent(id: string): ContentDetail {
  return useSWR<any>(`/api/content/${id}`, fetcherApiRoute);
}
 
const fetcherApiRoute = (url: string): Promise<any> => {
  return axios(url)
  .then((r) => r.data)
  .catch((err) => {
    console.info('error is ', err)
    throw err
  });
};

export default useFetchContent;

api路由内部


export default async (req, res): Promise<ContentDetail> => {
  const { id } = req.query;
  if (req.method === 'GET') {
   
    const fetchRealApi = await apiAxios(url);
   
  if(fetchRealApi) {
   // here depending on result of fetchRealApi i add some other fetch ... 
   return res.status(200).json({ ...fetchRealApi, complement: comp1 });
  }

  return res.status(500)

  }

  return res.status(500).json({ message: 'Unsupported method only GET is allowed' });
};


最后是 api axios 配置


const apiAxios = axios.create({
  baseURL: '/myBase',
});

apiAxios.interceptors.request.use(
  async (req) => {

    // HERE i am trying to get token from cookies
    // and also HERE if token is expired i am trying to refresh token
    config.headers.Authorization = token;
    req.headers['Content-type'] = 'application/x-www-form-urlencoded';
    return req;
  },
  (error) => {
    return Promise.reject(error);
  },
);

export default apiAxios;

我被困在这里,因为我在 apiAxios.interceptors.request.use 期间找不到令牌... 你知道我做错了什么吗,我是否以正确的方式处理这种行为?

【问题讨论】:

标签: axios jwt next.js


【解决方案1】:

如果您的 API 能够授权基于 cookie 的请求,Nilesh 的回答是正确的。它还需要 API 与您的前端应用程序位于同一域中。如果您需要将令牌发送到 API(cookie 中的那个),那么您将需要一个小型后端组件,通常称为 BFF 或令牌处理程序。它可以从 cookie 中提取令牌并放入 Authorization 标头中。

在 Curity,我们创建了此类令牌处理程序的示例实现,您可以从中获得启发:https://github.com/curityio/kong-bff-plugin/ 您还可以查看令牌处理程序模式的概述文章。

【讨论】:

    【解决方案2】:

    要允许向每个后续请求发送服务器 cookie,您需要将 withCredentials 设置为 true。这是代码。

    const apiAxios = axios.create({
      baseURL: '/myBase',
      withCredentials: true,
    });
    

    【讨论】:

    • 谢谢我错过了那部分。如果我想在 axios 拦截器中获取我的刷新令牌。如果我的令牌过期了,要更新它吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2014-07-26
    • 2019-04-07
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    相关资源
    最近更新 更多