2016-03-09 45 views
2

我想忽略对令牌认证如何忽略某些请求类型中Jsonwebtoken

被检查的一些API URL我要保护后放的方法,但没有获得此URL的

本地主机:3000/API /事件/

router.use(function(request, response) { 
    var token = request.body.token || request.query.token || request.headers['x-access-token']; 
    if (token) { 
     jwt.verify(token, app.get(superSecret), function(err, decoded) { 
      if (err) 
       return response.json({ 
        sucess: false, 
        message: "Failed token Authentication" 
       }); 
      else { 
       request.decoded = decoded; 
       next(); 
      } 

     }); 
    } else { 
     return response.status(403).send({ 
      success: false, 
      message: 'No token provided.' 
     }); 

    } 

}); 

我怎样才能做到这一点的节点使用jsonwebtoken,表达

我想这仅适用于POST,PUT,DELETE请求,但没有得到上重新任务。

+0

最简单的可能是把上面router.use的router.get那么router.use将仅适用于您在JS定义它下面的任何文件航线 – Molda

回答

0

您可以在匿名的中间件移动到正常声明的函数,然后把它传递给所有受保护的途径(您决定要保护哪条路线!)

你的代码可能看起来像:

function tokenProtection(request, response, next) { 
    var token = request.body.token || request.query.token || request.headers['x-access-token']; 
    if (token) { 
     jwt.verify(token, app.get(superSecret), function(err, decoded) { 
      if (err) 
       return response.json({ 
        sucess: false, 
        message: "Failed token Authentication" 
       }); 
      else { 
       request.decoded = decoded; 
       next(); 
      } 

     }); 
    } else { 
     return response.status(403).send({ 
      success: false, 
      message: 'No token provided.' 
     }); 

    } 

} 

现在你的路线可能看起来像(你的决定,你要保护的是什么):

router.get('/item', function(req, res) { ... }); // not protected 
router.get('/item/:id', function(req, res) { ... }); // not protected 
router.post(tokenProtection,'/item', function(req, res) { ... });//protected 
router.put(tokenProtection,'/item', function(req, res) { ... });//protected 

router.get('/book', function(req, res) { ... });// not protected 
router.get('/book/:id', function(req, res) { ... });// not protected 
router.post(tokenProtection,'/book', function(req, res) { ... });//protected 
router.put(tokenProtection,'/book', function(req, res) { ... });//protected 
+0

感谢answer.but我没有试过这种way.but我认为这是比我的更好的解决方案 – Rayees

0

把你的路线要在您的认证路径下保护,而您不想保护的认证路径以上。事情是这样的,

// Require what will be needed 
    var express = require('express'), 
    User  = require('../models/user'), 
    usersRouter = express.Router(); 

    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, 

    // Create a new user and return as json for POST to '/api/users' 
    usersRouter.post('/', function (req, res) { 
     var user = new User(req.body); 
     user.save(function(){ //pre-save hook will be run before user gets saved. See user model. 
     res.json({user : user, message: "Thank You for Signing Up"}); 

     }); 
    }); 

    usersRouter.post('/authentication_token', function(req, res){ 
     var password = req.body.password; 
     // find the user 
     User.findOne({ 
      email: req.body.email 
     }, function(err, user) { 
      //If error in finding the user throw the error 
      if (err) throw err; 
      //If there is no error and the user is not found. 
      if (!user) { 
      res.json({ success: false, message: 'Authentication failed. User not found.' }); 
      //if the user is found 
      } else if (user) { 
      // check if password matches 
      user.authenticate(password, function(isMatch){ 
       if(isMatch){ 
       // if user is found and password is right 
       // create a token with full user object. This is fine because password is hashed. JWT are not encrypted only encoded. 
       var token = jwt.sign({email: user.email}, secret.superSecret, { 
        expiresIn: 144000 
       }); 
       // set the user token in the database 
       user.token = token; 
       user.save(function(){ 
        // return the information including token as JSON 
        res.json({ 
        success: true, 
        id: user._id, 
        message: 'Enjoy your token!', 
        token: token 
        }); 
       }); 
       } else { 
       res.json({ success: false, message: 'Authentication failed. Wrong password.' }); 
       } 
      }); 
      } 
     }); 
     }); 

//***********************AUTHENTICATED ROUTES FOR USERS****************************** 

     // Return ALL the users as json to GET to '/api/users' 
    usersRouter.get('/', function (req, res) { 
     User.find({}, function (err, users) { 
     res.json(users); 
     }); 
    }); 

    // Export the controller 
    module.exports = usersRouter; 

其实我在我的博客昨天这本身说明,因为我努力弄明白。如果你还不清楚,你可以在这里查看,Node API Authentication with JSON Web Tokens - the right way

如果在我的情况下还有其他资源,这是计划。以下是我在所有想要认证的计划路线上放置的代码。

// 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.' 
    }); 

    } 
}); 
    //***********************AUTHENTICATED ROUTES FOR PLAN BELOW****************************** 
PlansController.get('/', function(req, res){ 
    Plan.find({}, function(err, plans){ 
    res.json(plans); 
    }); 
}); 
+0

谢谢你的回答。如果不同的路线在不同的文件中,我将输出它们全部。我有user.js文件中的用户路由和event.js文件中的事件路由 – Rayees

+0

@Rayees现在检查更新的答案。我包括计划路线和需要的认证。验证码位于路由上方。 – manutdfan