import { getServerSession } from 'next-auth/next';
import { authOptions } from '../../auth/[...nextauth]';
export default async function handler(
req, //: NextApiRequest,
res //: NextApiResponse
) {
const session = await getServerSession(req, res, authOptions);
let user = null;
if (session) user = session.user;
else {
const token = req.headers.get('Authorization').replace(/^Bearer /, '');
user = await validateToken(token);
if(!user){ //validate token and generate the user defined by your external caller
res.status(401).end();
return;
}
}
// do work with authenticated user;
// since your comment about needing a cookie for an upstream server:
fetch('upsteamurl', {
headers:{
'Set-Cookie': makeCookieHeader(req.query.monitor, 'sent', {path:'/', secure:false, sameSite:'strict', httpOnly:false}))
}
}).then(... // use the upstream response
...
}
function makeCookieHeader(name, value, opts){
let header = name +'='+value;
if(opts){
if (opts.maxAge) opts.expires = new Date(Date.now() + opts.maxAge);
if (opts.path ) header += '; path=' + opts.path;
if (opts.expires ) header += '; expires=' + opts.expires.toUTCString();
if (opts.domain ) header += '; domain=' + opts.domain;
if (opts.sameSite ) header += '; samesite=' + (opts.sameSite === true ? 'strict' : opts.sameSite.toLowerCase());
if (opts.secure ) header += '; secure';
if (opts.httpOnly ) header += '; httponly';
}
return header;
}
1条答案
按热度按时间wlwcrazw1#
您需要在API调用中提供备用身份验证。例如,在API路由上使用NextAuth
例如