适用于NodeJS和Auth0的JWT Auth

时间:2018-06-27 20:20:15

标签: node.js jwt auth0

我正在使用Auth0在正在开发的MEAN应用上进行用户身份验证。我遇到的问题是我已将模型,路由和控制器分离到单独的文件中。我正在遵循Auth0教程,以指导在何处使用JWT令牌认证,但是我不确定它在我的设置中的位置。

checkJwt属于哪里?

https://auth0.com/docs/quickstart/backend/nodejs/01-authorization

锻炼路由器

module.exports = function(app) {
    var workouts = require('../controllers/workoutController');

    // workout Routes
    app.route('/api/workouts')
      .get(workouts.getAllWorkouts)
      .post(workouts.createWorkout);

    app.route('/api/workouts/benchmarks')
    .get(workouts.getBenchmarks);

    app.route('/api/workouts/:workoutId')
      .get(workouts.getWorkout)
      .put(workouts.updateWorkout)
      .delete(workouts.deleteWorkout);
  };

对应控制器

var mongoose = require('mongoose'),
  Workout = mongoose.model('Workout');

exports.getAllWorkouts = function(req, res) {
  Workout.find({}, function(err, workouts) {
    if (err)
      res.send(err);
    res.json(workouts);
  });
};


exports.getBenchmarks = function(req, res) {
  Workout.find({
    "type":"Benchmark"
  }, function(err, workouts) {
    if (err)
      res.send(err);
    res.json(workouts);
  });
};

exports.createWorkout = function(req, res) {
  var newWorkout = new Workout(req.body);
  newWorkout.save(function(err, workout) {
    if (err)
      res.send(err);
        res.json(workout);
  });
};

exports.getWorkout = function(req, res) {
  Workout.findById(req.params.workoutId, function(err, workout) {
    if (err)
      res.send(err);
    res.json(workout);
  });
};


exports.updateWorkout = function(req, res) {
  Workout.findOneAndUpdate({_id: req.params.workoutId}, req.body, {new: true}, function(err, workout) {
    if (err)
      res.send(err);
    res.json(workout); 
  });
};

exports.deleteWorkout = function(req, res) {
  Workout.remove({
    _id: req.params.workoutId
  }, function(err, workout) {
    if (err)
      res.send(err);
    res.json({ message: 'Workout successfully deleted' });
  });
};

锻炼帖子()

exports.createWorkout = function(req, res) {
  var newWorkout = new Workout(req.body);
  newWorkout.save(function(err, workout) {
    if (err)
      res.send(err);
        res.json(workout);
  });
};

1 个答案:

答案 0 :(得分:1)

首先,您应该在单独的文件中配置checkJwt(例如在docs中),并在路由器文件中要求它。

让我们看看如何在锻炼路由器中protect the routes

module.exports = function(app) {
    var workouts = require('../controllers/workoutController');
    var checkJwt = require('./path/to/checkJwt');

    // workout Routes
    app.route('/api/workouts')
      .get(workouts.getAllWorkouts) // unprotected route
      .post(checkJwt, workouts.createWorkout); // protected route

    app.route('/api/workouts/benchmarks')
    .get(workouts.getBenchmarks);

    app.route('/api/workouts/:workoutId')
      .get(workouts.getWorkout)
      .put(workouts.updateWorkout)
      .delete(workouts.deleteWorkout);
};

函数checkJwt是一个中间件,可在到达控制器逻辑之前检查请求是否已通过身份验证。

checkJwt文件:

var checkJwt = jwt({
  ...
})

module.exports = checkJwt