Home > Enterprise >  How can we reuse basic authentication session for http get and put requests in NodeJS?
How can we reuse basic authentication session for http get and put requests in NodeJS?

Time:03-04

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));


    });
} 

CodePudding user response:

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

  • Related