OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Authorization missing or empty after setting Headers

  • Thread starter Thread starter Deltag0ny
  • Start date Start date
D

Deltag0ny

Guest
I've been trying to add set the authorization in my headers after a user logs in, but no matter what I've tried, the authorization field is either empty or missing.

If I log in from my application on the web and log what I get like this:

Code:
console.log("AccessTokenHere"); // I get the correct token
console.log("Logged in!");
res.header('Authorization', "Bearer " + accessToken);
console.log(req.headers);

This is what I get back:

Code:
{host: 'localhost:5001', connection: 'keep-alive', content-length: '48', cache-control: 'max-age=0', sec-ch-ua: '"Google Chrome";v="125", "Chromium";v="125", "Not.A/Brand";v="24"', …}
accept:'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'
accept-encoding:'gzip, deflate, br, zstd'
accept-language:'en-CA,en;q=0.9,fr-CA;q=0.8,fr;q=0.7,en-US;q=0.6'
cache-control:'max-age=0'
connection:'keep-alive'
...

Authorization is nowhere to be seen.

Doing this on thunderClient though, I get an additional authorization:'' line.

I'm sending a post request through my login function:

Code:
const express = require("express");
const appUser = express();
const User = require("../models/userModel");
const dotenv = require("dotenv");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const asyncHandler = require("express-async-handler");
const bodyParser = require("body-parser");
const mustache = require('mustache');
const path = require("path");
var engine = require('consolidate');
const http = require('http');
appUser.use(express.json());

appUser.set('views', __dirname + '/views');
appUser.engine('html', engine.mustache);
appUser.set('view engine', 'html');
appUser.use(bodyParser.urlencoded({ extended: true }));

const login = asyncHandler (async (req, res) => {
    const email = req.body.email;
    const password = req.body.Password;
    console.log(`${email}, ${password}`)
    if (!email || !password){
        res.status(400);
        throw new Error("Email or password not provided");
    }
    const user = await User.findOne({email});
    if (user && (await bcrypt.compare(password, user.password))) {
        const accessToken = jwt.sign({
            user: {
                username: user.id,
                email: user.email,
                id: user.id
            },
        }, process.env.ACCESS_TOKEN_SECRET,
        {expiresIn: "30m"});
        console.log("AccessTokenHere");
        console.log("Logged in!");
        res.header('Authorization', "Bearer " + accessToken);
        console.log(req.headers);
        res.redirect(302, "/home/user/userPAGE");
    }
    else {
        res.status(400);
        throw new Error("Email or Password is not valid");
    }

});

Which then is supposed to redirect to another page after verification that the token is good by this function:

Code:
const asyncHandler = require("express-async-handler");
const jwt = require("jsonwebtoken");

const validateToken = asyncHandler(async (req, res, next) => {
    let token;
    let authHeader = String(req.headers['authorization'] || '');
    console.log(req.headers);
    console.log("boop");
    if (authHeader.startsWith("Bearer ")) {
        token = authHeader.split(" ")[1];
        console.log("hey");
        jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
            if (err) {
                res.status(400);
                throw new Error("User is not authorized");
            }
            req.decoded = decoded.user;
            next();
        });
        if (!token) {
            res.status(401);
            throw new Error("User is not authorized or token is missing");
        }
    }
    else {
        res.status(401);
        throw new Error("User is not authorized or token is missing");
    }
});

But we don't even get there. I've tried to use res.setHeader also, but that didn't work and other posts with this similar issue didn't help.

<p>I've been trying to add set the authorization in my headers after a user logs in, but no matter what I've tried, the authorization field is either empty or missing.</p>
<p>If I log in from my application on the web and log what I get like this:</p>
<pre><code>console.log("AccessTokenHere"); // I get the correct token
console.log("Logged in!");
res.header('Authorization', "Bearer " + accessToken);
console.log(req.headers);
</code></pre>
<p>This is what I get back:</p>
<pre><code>{host: 'localhost:5001', connection: 'keep-alive', content-length: '48', cache-control: 'max-age=0', sec-ch-ua: '"Google Chrome";v="125", "Chromium";v="125", "Not.A/Brand";v="24"', …}
accept:'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7'
accept-encoding:'gzip, deflate, br, zstd'
accept-language:'en-CA,en;q=0.9,fr-CA;q=0.8,fr;q=0.7,en-US;q=0.6'
cache-control:'max-age=0'
connection:'keep-alive'
...
</code></pre>
<p>Authorization is nowhere to be seen.</p>
<p>Doing this on thunderClient though, I get an additional <code>authorization:''</code> line.</p>
<p>I'm sending a post request through my login function:</p>
<pre><code>const express = require("express");
const appUser = express();
const User = require("../models/userModel");
const dotenv = require("dotenv");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const asyncHandler = require("express-async-handler");
const bodyParser = require("body-parser");
const mustache = require('mustache');
const path = require("path");
var engine = require('consolidate');
const http = require('http');
appUser.use(express.json());

appUser.set('views', __dirname + '/views');
appUser.engine('html', engine.mustache);
appUser.set('view engine', 'html');
appUser.use(bodyParser.urlencoded({ extended: true }));

const login = asyncHandler (async (req, res) => {
const email = req.body.email;
const password = req.body.Password;
console.log(`${email}, ${password}`)
if (!email || !password){
res.status(400);
throw new Error("Email or password not provided");
}
const user = await User.findOne({email});
if (user && (await bcrypt.compare(password, user.password))) {
const accessToken = jwt.sign({
user: {
username: user.id,
email: user.email,
id: user.id
},
}, process.env.ACCESS_TOKEN_SECRET,
{expiresIn: "30m"});
console.log("AccessTokenHere");
console.log("Logged in!");
res.header('Authorization', "Bearer " + accessToken);
console.log(req.headers);
res.redirect(302, "/home/user/userPAGE");
}
else {
res.status(400);
throw new Error("Email or Password is not valid");
}

});
</code></pre>
<p>Which then is supposed to redirect to another page after verification that the token is good by this function:</p>
<pre><code>const asyncHandler = require("express-async-handler");
const jwt = require("jsonwebtoken");

const validateToken = asyncHandler(async (req, res, next) => {
let token;
let authHeader = String(req.headers['authorization'] || '');
console.log(req.headers);
console.log("boop");
if (authHeader.startsWith("Bearer ")) {
token = authHeader.split(" ")[1];
console.log("hey");
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
res.status(400);
throw new Error("User is not authorized");
}
req.decoded = decoded.user;
next();
});
if (!token) {
res.status(401);
throw new Error("User is not authorized or token is missing");
}
}
else {
res.status(401);
throw new Error("User is not authorized or token is missing");
}
});
</code></pre>
<p>But we don't even get there.
I've tried to use res.setHeader also, but that didn't work and other posts with this similar issue didn't help.</p>
 

Latest posts

Top