2016-06-08 30 views
1

我執行JWT授權每個API象下面這樣:處理快速,智威湯遜錯誤在可組合的中間件

auth.js

import expressJwt from 'express-jwt'; 
import compose from 'composable-middleware'; 

var validateJwt = expressJwt({ 
    secret: config.secrets.session 
}); 

function isAuthenticated() { 
    return compose() 

    .use(function(req, res, next) { 
     validateJwt(req, res, next); 
    }) 
    .use(function(req, res, next) { 

    User.find({ 
      where: { 
     id: req.user.id 
      } 
    }).then(function(user){ 

      //Handle User 
     }).catch(function(err){ 
      //Handle DB Error 
     }); 
    }); 
} 

index.js

import auth from '../../auth'; 
import express from 'express'; 
import controller from './user_group.controller'; 
import * as validators from './user_group.validations'; 

// Create router object 
const router = express.Router(); 

// Get all user groups 
router.get('/', [auth.isAuthenticated(), validators.index], controller.index); 

除了JWT的錯誤處理外,一切工作都很好。我不理解validateJwt(req, res, next);函數在處理下一個中間件之前如何處理Unauthorized Error stack

回答

2

我使用下面的做到了:

.use(function(err, req, res, next) { 

    if(err) { 
    return res.status(constants.INVALID_OR_NO_ACCESS_TOKEN.code).json({ 
     status: 'error', 
     code: constants.INVALID_OR_NO_ACCESS_TOKEN.code, 
     message: constants.INVALID_OR_NO_ACCESS_TOKEN.message 
    }).end(); 
    } 
    User.find({ 
    where: { 
     id: req.user.id 
    } 
    }) 
+1

這工作後再添。使用,但是,它不能捕捉「語法錯誤:意外的令牌 」錯誤... – KiwenLau

0

可以validateJwt

return compose() 
     .use(function(req,res,next){ 
      validateJwt(req, res, next); 
      }) 
     .use(function(req,res,next){ 
       if(err){ 
       //here you will catch the error generated by the validateJWT  
       } 
       else{ 
        next(); 
       } 

      })