首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我怎么能在阿西奥斯传递曲奇?

我怎么能在阿西奥斯传递曲奇?
EN

Stack Overflow用户
提问于 2021-12-08 04:43:06
回答 2查看 1.6K关注 0票数 2

我在next-js应用程序中,我的令牌存储在cookie中。出于某些原因,我使用Swr和Api路由来获取我的安全api后端。我正在设法在所有api请求中放置我的auth令牌。

在登录期间,cookie被设置为

代码语言:javascript
复制
  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的页面示例。

代码语言:javascript
复制
//page/test.ts - example of my test route

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

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

  return <DisplayContent content={data} />

这是一个swrFetchHook

代码语言:javascript
复制
// 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路由

代码语言:javascript
复制
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配置。

代码语言:javascript
复制
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.你知道我做错了什么吗,我有一个正确的方法来处理这种行为吗?

EN

回答 2

Stack Overflow用户

发布于 2021-12-08 04:59:43

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

代码语言:javascript
复制
const apiAxios = axios.create({
  baseURL: '/myBase',
  withCredentials: true,
});
票数 1
EN

Stack Overflow用户

发布于 2021-12-08 12:00:57

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70270059

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档