简体   繁体   中英

No authorization token was found when res.redirect

I have two applications, both on Nodejs. One front-end and other back-end. My back-end app is protected with token access using express-jwt and jsonwebtoken middlewares.

My problem is: I am making a request from front-end to back-end passing the token on header, back-end accepts the request and respond properly. Then in the front-end I redirect the response to an specific page ( res.redirect('/') ), in that moment I get the error UnauthorizedError: No authorization token was found

My front-end request:

/* Authentication */
router.post('/', function(req, res, next) {

    // request login service
    request({
        uri: env.getUrl() + "/user",
        method: 'POST',
        timeout: 10000,
        headers: {
            'Authorization': 'Bearer '.concat(global.token)
        },
        form: { login : req.body.login, pwd : req.body.pwd }
    }, function(error, response, body){
        if(error) {
            logger.error(error);
            res.render("error", {message: "Error getting user" }); 
        }
        else {
            if(body){
                req.session.usuario = JSON.parse(body);
                res.redirect("/");
            } else {
                res.render("login", {message: "Login Failed" });
            }
        }
    });
});

I don't know why this happen. Could you help me? Thanks in advance.

A redirect (via res.redirect ) issues a new HTTP request. This means that the Authorization header is empty. This results in the UnauthorizedError error.

To fix this, you have two options:

1. Pass the token in the URI
You can issue the redirect with the token passed in the URL in this way:

res.redirect("/?access_token=" + global.token);

2. Set the header before the redirect
You can set the 'Authorization' header before making the redirect request:

req.session.access_token = global.token;

Problem found.

Anytime the my front-end app makes a request to the back-end side (api) the user logged in front-end is validated against back-end and so the fron-end's session is updated as well. Which means that every request is actually two requests:

  1. One as the real request the app is doing.
  2. The request validating the user logged on front-end in order to be sure that user exists.

This update (second point) was made without providing a token.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM