简体   繁体   中英

Secure Vercel Next.js serverless function using auth

I want to make my GraphQL API available only to authenticated users. I use apollographql studio to test my 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.

在此处输入图像描述

Serverless function on Vercel

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

{
  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:

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM