Correct way to protect url with JSON token and node.js / express

I am currently allowing users to use JSON tokens with node.js and express with EJS as their viewer.

Using simple middleware in server.js file:

app.use(function(request, response, next){
        var token = request.body.token || request.query.token || request.headers['x-access-token'];
        console.log(request.body);
        if(token){
        jwt.verify(token, app.get('superSecret'), function(err, decoded){
                   if(err){
                   response.json({"message": "Failed to authenticate user"});
                   }
                   else{
                   request.decoded = decoded;
                   next();
                   }
                   });
        }
        else{
        return response.status(403).json({"message":"No token was provided"});
        }
        });

      

and protected routes below it, for example:

app.post('/userlist', function(request, response) {
        response.json({some: json})
        });

      

I cannot figure out or figure out how to secure the GET route, for example:

app.get('/userprofile', function(request, response) {
            response.render('pages/userprofile');
            });

      

If I make a request to some url directly www.example.com/userprofile

, access is denied because the request does not include a token.

If I do this via ajax:

$.ajax({
           type:"GET",
           url:"https://www.example.com/userprofile",
           headers:{"x-access-token": token },
           success: function(result, success){
           },
           error: function (result, error){
           }
       });

      

The answer is not displayed, but returned in the result object. I have wires here.

+1


source to share


2 answers


You must pass a token to use it. If the server does not have access to it, the server cannot verify it. So, you can pass the token in the path:

app.get('/userprofile/:token',function(request,response){
  console.log(request.params.token);
});

      

In the query string:



app.get('/userprofile',function(request,response){
  console.log(request.query.token);
});

      

Or as a cookie:

var cookieParser = require('cookie-parser');
app.use(cookieParser);
app.get('/userprofile',function(request,response){
  console.log(request.cookies.token);
});

      

+2


source


HTTP response code should be sent, default 200 like in your case response.json({"message": "Failed to authenticate user"});



try response.json(401, {"message": "Failed to authenticate user"});

0


source







All Articles