Header authorization doesn't exist

Viewed 774

I'm trying to send a jwt token on my API but it doesn't work whereas i do the same thing as an internet course. And it seems like the authorization header is undefined and don't take the token i give in a json response.

Here is a screenshot of my login function :

login(req:Request, res:Response) {
    const id = this._id;
    bcrypt.compare(req.query.password, this._password)
        .then(function (valid: any) {
            if (!valid) {
                return res.status(401).json({error: 'Mot de passe incorrect !'});
            }
            res.status(200).json({
                hostId: id,
                token: jwt.sign({hostId : id}, 'RANDOM_TOKEN_SECRET', {expiresIn: '12h'})
                });
            })
            .catch(function (error:any) {
                res.status(500).json({error})
            })
        .catch(function (error:any)  {
            res.status(500).json({error});
        });
}

And here is my authentification function :

static auth(req: Request, res: Response, next: any) {
    try {
        console.log('bonjour');
        console.log(req.headers.authorization);
        console.log(req.body.hostId);
        let token = req.headers.authorization?.split(' ')[1];
        const decodedToken = jwt.verify(token, 'RANDOM_TOKEN_SECRET');
        const id = decodedToken.hostId;
        if (req.body.hostId && req.body.hostId !== id) {
            throw 'Invalid user ID';
        } else {
            next();
        }
    } catch (error) {
        res.status(401).json({error: error.message});
    }
}

And I have setup my headers in my server class :

export default class Server {
constructor() {
    app.use(function (req:Request, res:Response, next:any) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Authorization, Content-Type, Accept");
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
        next();
    })
    .get('/', function (req:Request, res:Response) {
        res.send("Serveur démarré");
    })
    .listen(8080);
}

}

I'm using nodejs with express, mongoose for my db and typescript.

I hope you can help me :)

1 Answers

You should set header as { Authorization: Bearer ${token} } in front-end side instead of server side

Related