How do I add a json web token to each header?

后端 未结 3 737
日久生厌
日久生厌 2021-02-09 02:39

So I am trying to use JSON web tokens for authentication and am struggling trying to figure out how to attach them to a header and send them on a request.

I was trying t

3条回答
  •  轮回少年
    2021-02-09 02:55

    Here is an example from Angular code to get plans for instance, you just write it like this,

     $scope.getPlans = function(){
        $http({
          url: '/api/plans',
          method: 'get',
          headers:{
            'x-access-token': $rootScope.token
          }
        }).then(function(response){
          $scope.plans = response.data;
        });
      }
    

    and on your server, you can do this,

    var jwt    = require('jsonwebtoken'); // used to create, sign, and verify tokens
    var config = require('./config'); // get our config file
    
    var secret = {superSecret: config.secret}; // secret variable
    
    // route middleware to verify a token. This code will be put in routes before the route code is executed.
    PlansController.use(function(req, res, next) {
    
      // check header or url parameters or post parameters for token
      var token = req.body.token || req.query.token || req.headers['x-access-token'];
    
      // If token is there, then decode token
      if (token) {
    
        // verifies secret and checks exp
        jwt.verify(token, secret.superSecret, function(err, decoded) {
          if (err) {
            return res.json({ success: false, message: 'Failed to authenticate token.' });
          } else {
            // if everything is good, save to incoming request for use in other routes
            req.decoded = decoded;
            next();
          }
        });
    
      } else {
    
        // if there is no token
        // return an error
        return res.status(403).send({
            success: false,
            message: 'No token provided.'
        });
    
      }
    });
    
    // Routes
    PlansController.get('/', function(req, res){
      Plan.find({}, function(err, plans){
      res.json(plans);
      });
    });
    

    If you are still not clear, you can check out the details on my blog post here, Node API Authentication with JSON Web Tokens - the right way.

提交回复
热议问题