Mohammad Awais
Mohammad Awais

Reputation: 35

how to send jwt token to a middleware in a get request in express node.js

Js and web development I've tried searching the web crazy but I couldn't find a solution that could help me...

I have completed creating a project for a small lab...now I'm trying to create its login page and creating a web token using JWT...

I manage to successfully create a user and hash user password using bcrypt.... and successfully create an access token and refresh token....

I have also created a middleware that will authenticate the token

now I don't know how to send the token to that middleware

This is the authenticate token function

function authenticateToken(req, res, next)
{ 
    try {
        // header contains the token
        // format
        // Bearer Token
        // inside autherization header
        var authHeader = req.headers['authorization'];

        var token = authHeader && authHeader.split(' ')[1]

        if (token == null) {
            // Meaning the user has not send a token.
            // return res.sendStatus(401);
            res.redirect('/login/');
        }
        // req.token = token;
        // let headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token });

        jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user)=>{
            if (err) {
                console.log("invalid token");
                res.redirect('/login/');
                return res.sendStatus(403);
                // invalid token
            }

            req.user = user;
            next();
        });
    } catch (error) {
        return res.send(error.message);
    }
}

I will not post all the data as its not relevant as it will populate the text area and will increase the difficulty level in understanding.... I will only share the part where I'm stuck.

this is the part where I check if the user exists and password is correct after successful authentication then I want to redirect to the dashboard page...or the main page 

I cant send the access token to the route with the middleware of user authentication


router.post('/authenticate', (req,res,next)=>{
    // console.log("Authenticate");
    // console.log(req.body);
    // console.log("Authenticate");

    var email = req.body.email;
    var password = req.body.password;

    var sqlQuery = "select * from user where email  = '"+email+"' and display = 'yes' ;;";
    try {
        con.query(sqlQuery,(error,result)=>{
            if (!error) {
                // console.log(result);
                var oriPassword = result[0].PASSWORD;

                var user = 
                {
                    id : result[0].ID,
                    name : result[0].LASTNAME,
                    mobileNo : result[0].MOBILENO,

                };

                bcrypt.compare(password, oriPassword,(err,res)=>{
                    if (!err) {
                        var accessToken = generateAccessToken(user);
                        var refreshToken = jwt.sign(user, process.env.REFRESH_TOKEN_SCRET);

                        sqlQuery = "update user set AccessToken = '"+accessToken+"' ,refreshtoken = 
 '"+refreshToken+"' where id = "+user.id+";";

                        con.query(sqlQuery,(error,result)=>{
                            if (!error) {
                                console.log("RefreshToken Inserted.");
                                console.log({accessToken:accessToken, refreshToken:refreshToken});
                               req.headers.authorization = accessToken;

                            } else {
                                console.log(error.message);
                            }
                        });

                    } 
                    else {

                    }
                });
                console.log("redirecting to login user");
                // console.log("Response Header");
                // console.log(res.header.authorization );
                res.redirect('/login/loginUser');
                // res.send({accessToken:accessToken, refreshToken:refreshToken});
            } else {
                console.log(error.message);
            }
        });
    } catch (error) {
        console.log(error.message);
    }

});

the route I want to go

router.get('/loginUser',authenticateToken,(req,res,next)=>{
    // console.log(req.user);

    // res.render("pages/dashboard/index");
    // res.redirect("/");
    res.send("Success");
    console.log("Login SuccessFull..");
});

please help me I'm stuck in this form 3 days...

Upvotes: 1

Views: 2715

Answers (2)

Kasunaz
Kasunaz

Reputation: 593

You can parse request header to the route with the token like this.

enter image description here

And you can access that token in the middleware function by using this function.

function getTokenFromHeader() {
  if (
    (req.headers.authorization &&
      req.headers.authorization.split(' ')[0] === 'Token') ||
    (req.headers.authorization &&
      req.headers.authorization.split(' ')[0] === 'Bearer')
  ) {
    return req.headers.authorization.split(' ')[1];
  }

  return null;
}

Upvotes: 1

Kishor
Kishor

Reputation: 450

From what i get, you want to send some data(in this case, access token) to a certain route. You can always use query strings. Check out how it is used here.

However, I am not sure if passing around tokens in non-public api is secure.

Upvotes: 1

Related Questions