我在next-js应用程序中,我的令牌存储在cookie中。出于某些原因,我使用Swr和Api路由来获取我的安全api后端。我正在设法在所有api请求中放置我的auth令牌。
在登录期间,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.你知道我做错了什么吗,我有一个正确的方法来处理这种行为吗?
发布于 2021-12-08 04:59:43
要允许向每个后续请求发送服务器cookie,需要将withCredentials设置为true。这是密码。
const apiAxios = axios.create({
baseURL: '/myBase',
withCredentials: true,
});发布于 2021-12-08 12:00:57
如果您的API能够基于cookie授权请求,那么Nilesh的回答是正确的。另外,它还需要API与您的前端应用程序位于同一个域中。如果您需要将令牌发送到API (cookie中的令牌),那么您将需要一个小型后端组件(通常称为BFF或令牌处理程序)。它可以从cookie中提取令牌并放入授权头。
在Curity中,我们创建了这样一个令牌处理程序的示例实现,您可以从中得到启发:https://github.com/curityio/kong-bff-plugin/,您还可以查看令牌处理程序模式的概述文章。
https://stackoverflow.com/questions/70270059
复制相似问题