我们如何在 NodeJS 中重用 http get 和 put 请求的基本身份验证会话?

发布于 2025-01-09 21:39:11 字数 3562 浏览 0 评论 0原文

在下面的代码中,您可以看到具有基本身份验证的函数:makeGET() 和 makePUT(); 此外,您看到的这些代码正在开发中,它们目前正在完成自己的工作。 我需要做的是,在基本身份验证之后,在所有后续调用中重用会话。

正如您所看到的表单代码,我尝试将标头 'set-cookie' 存储在变量中并重用它。

我在互联网上花了几个小时,但无法为这个问题创建解决方案。 您能否推荐并展示在 NodeJS 中重用 http 请求上的基本身份验证会话的正确方法?

此外,当我尝试通过 PUT 请求存储和重用 cookie 时,服务器会阻止请求并出现 CSRF 错误。如何才能解决这些问题呢?

谢谢

let authCookie = null;

function makeGET(url, user, pass) {
    
    let reqHeaders = {
                    'Accept': 'application/json'
                };
    if(authCookie){
        reqHeaders['Cookie'] = authCookie;
    }
    return new Promise((resolve, reject) => {
        http.get(
            url,
            {
                auth: user+':'+pass,
                headers: reqHeaders
            },
            (res) => {
                const { statusCode } = res; 
                 
                const contentType = res.headers['content-type'];
                
                if(res.headers['set-cookie'] && res.headers['set-cookie'][0]){
                    authCookie = res.headers['set-cookie'][0];
                }
                 

                let error;
                if (statusCode !== 200) {
                    error = new Error('Request Failed.\n' +
                        `Status Code: ${statusCode}`);
                } else if (!/^application\/json/.test(contentType)) {
                    error = new Error('Invalid content-type.\n' +
                        `Expected application/json but received ${contentType}`);
                }
                if (error) {
                    authCookie = null;
                    console.error(error.message);
                    // Consume response data to free up memory
                    res.resume();
                    //resolve("");
                    return;
                } 

                res.setEncoding('utf8');
                let rawData = '';
                res.on('data', (chunk) => {
                    //console.log(chunk) 
                    rawData += chunk;
                });
                res.on('end', () => {

                    try {
                        resolve(rawData);
                    } catch (e) {
                        authCookie = null;
                        console.error(e.message);
                        resolve("");
                    }
                });
            }).on('error', (e) => {
                authCookie = null;
                console.error(`Got error: ${e.message}`);
                resolve("");
            });
    });
}

 
function makePUT(host, port, path, user, pass, data) {
    return new Promise((resolve, reject) => {

        const options = {
            host: host,
            port: port,
            path: path,
            method: 'PUT',
            headers: {
                'Authorization': 'Basic ' + Buffer.from(user + ":" + pass).toString('base64'),       
                "Content-Type": "application/json"
            }
        }

        const req = http.request(options, (res) => {
            console.log(`statusCode: ${res.statusCode}`)
            console.log(`message: ${res.statusMessage}`)
            // console.log(res.headers) 
            resolve("success");
            res.on('data', (d) => {
                //process.stdout.write(d)
            })
        })

        req.on('error', (error) => {
            console.error(error)
            resolve("error");
        })

        //req.write("")//data
        req.end(JSON.stringify(data));


    });
} 

In following code you see to functions with basic authentication: makeGET() and makePUT();
Also these code you see are work in progress, they currently are doing their job.
What I need to do is, after basic authentication reuse session in all subsequent calls.

As you can see form code I tried to store header 'set-cookie' in variable and reuse it.

I have spent hours on internet but unable to create solution for this problem.
Could you please recommend and show correct way to reuse basic authentication session on http requests in NodeJS?

Also when I try to store and reuse cookie with PUT request, server blocks request with CSRF error. How is it possible to solve these problems?

Thank you

let authCookie = null;

function makeGET(url, user, pass) {
    
    let reqHeaders = {
                    'Accept': 'application/json'
                };
    if(authCookie){
        reqHeaders['Cookie'] = authCookie;
    }
    return new Promise((resolve, reject) => {
        http.get(
            url,
            {
                auth: user+':'+pass,
                headers: reqHeaders
            },
            (res) => {
                const { statusCode } = res; 
                 
                const contentType = res.headers['content-type'];
                
                if(res.headers['set-cookie'] && res.headers['set-cookie'][0]){
                    authCookie = res.headers['set-cookie'][0];
                }
                 

                let error;
                if (statusCode !== 200) {
                    error = new Error('Request Failed.\n' +
                        `Status Code: ${statusCode}`);
                } else if (!/^application\/json/.test(contentType)) {
                    error = new Error('Invalid content-type.\n' +
                        `Expected application/json but received ${contentType}`);
                }
                if (error) {
                    authCookie = null;
                    console.error(error.message);
                    // Consume response data to free up memory
                    res.resume();
                    //resolve("");
                    return;
                } 

                res.setEncoding('utf8');
                let rawData = '';
                res.on('data', (chunk) => {
                    //console.log(chunk) 
                    rawData += chunk;
                });
                res.on('end', () => {

                    try {
                        resolve(rawData);
                    } catch (e) {
                        authCookie = null;
                        console.error(e.message);
                        resolve("");
                    }
                });
            }).on('error', (e) => {
                authCookie = null;
                console.error(`Got error: ${e.message}`);
                resolve("");
            });
    });
}

 
function makePUT(host, port, path, user, pass, data) {
    return new Promise((resolve, reject) => {

        const options = {
            host: host,
            port: port,
            path: path,
            method: 'PUT',
            headers: {
                'Authorization': 'Basic ' + Buffer.from(user + ":" + pass).toString('base64'),       
                "Content-Type": "application/json"
            }
        }

        const req = http.request(options, (res) => {
            console.log(`statusCode: ${res.statusCode}`)
            console.log(`message: ${res.statusMessage}`)
            // console.log(res.headers) 
            resolve("success");
            res.on('data', (d) => {
                //process.stdout.write(d)
            })
        })

        req.on('error', (error) => {
            console.error(error)
            resolve("error");
        })

        //req.write("")//data
        req.end(JSON.stringify(data));


    });
} 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

机场等船 2025-01-16 21:39:11

我觉得很愚蠢,我们使用的是 referrer 而不是 referrer。当我们使用正确的名称设置 referer 标头时,会话现在被重用。

I feel so silly, we were using referrer instead of referer. When we set referer header with correct name, session is being reused now.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文