[英]Secure Vercel Next.js serverless function using auth
I want to make my GraphQL API available only to authenticated users.我想让我的 GraphQL API 仅对经过身份验证的用户可用。 I use apollographql studio to test my API.
我使用 apollographql studio 来测试我的 API。 I have set the auth token in the header, but I don't know how to read the token in the serverless function using Next.js and Vercel.
我已经在 header 中设置了身份验证令牌,但我不知道如何使用 Next.js 和 Vercel 读取无服务器 function 中的令牌。
Serverless function on Vercel Vercel 上的无服务器 function
export default async function handler(req: VercelRequest, res: VercelResponse) {
console.debug(req.headers);
console.debug(req.headers.authorization)
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader(
'Access-Control-Allow-Origin',
'https://studio.apollographql.com'
);
res.setHeader(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
if (req.method === 'OPTIONS') {
res.end();
return false;
}
await startLocalServer;
await apolloServerLocal.createHandler({
path: '/api/graphql',
})(req, res);
}
}
export const apolloServerLocal = new ApolloServer({
schema: schema,
introspection: true,
});
export const startLocalServer = apolloServerLocal.start();
Output Output
{
host: 'localhost:3000',
connection: 'keep-alive',
accept: '*/*',
'access-control-request-method': 'POST',
'access-control-request-headers': 'authorization,content-type',
origin: 'https://studio.apollographql.com',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'cross-site',
'sec-fetch-dest': 'empty',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9,de-DE;q=0.8,de;q=0.7'
}
undefined
What I did for my application was to set the same key in vercel's environment variable then in the handler function, do something like this:我为我的应用程序所做的是在 vercel 的环境变量中设置相同的键,然后在处理程序 function 中,执行以下操作:
// protect route by checking secret key
if (
!req.headers.authorization ||
req.headers.authorization !== process.env.SECRET
)
return res.status(401).send('Not authorized');
rest of your logic
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.