4

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.

4

2 回答 2

1

重定向(通过res.redirect)发出一个新的 HTTP 请求。这意味着Authorization标题为空。这会导致UnauthorizedError错误。

要解决此问题,您有两种选择:

1. 在 URI 中传递令牌
您可以通过以下方式使用 URL 中传递的令牌发出重定向:

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

2. 重定向前
设置header 可以'Authorization'在重定向请求前设置header:

req.session.access_token = global.token;
于 2016-03-08T14:14:42.803 回答
0

发现问题。

每当我的前端应用程序向后端 (api) 发出请求时,登录前端的用户都会针对后端进行验证,因此前端的会话也会更新。这意味着每个请求实际上是两个请求:

  1. 一个作为应用程序正在执行的真正请求。
  2. 验证用户登录前端的请求,以确保该用户存在。

此更新(第二点)是在未提供令牌的情况下进行的。

于 2016-03-12T23:45:57.357 回答