next.js 将访问令牌转换为Cookie或支持基于访问令牌的身份验证

sshcrbum  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(128)

我有React + Next JS + auth 0 Web应用程序,它使用基于会话/cookie的身份验证来保护页面和API。我想从其他地方以编程方式调用其中一个API,而进行API调用所需的唯一凭据是获取访问令牌。我正在寻找两种可能的解决方案之一:
1.如何在客户端使用访问令牌生成cookie以调用Web应用程序?

  1. nextjs+react+ auth 0 web应用程序如何接受访问令牌作为凭据?
    因为我管理代码的两端,所以我对任何解决方案都持开放态度。
wlwcrazw

wlwcrazw1#

您需要在API调用中提供备用身份验证。例如,在API路由上使用NextAuth
例如

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;

}

相关问题