2013-10-24 32 views
1

我是新來表達,而我通過實施中間件來處理X-Hub-Signature這裏描述得過且過:https://pubsubhubbub.googlecode.com/git/pubsubhubbub-core-0.4.html#authednotify驗證PubSubHubbub通訊內容簽名

我想添加一箇中間件手柄在將請求傳遞到標準的express.json()中間件之前,實際解碼身體。

var sigVerifier = function(req, res, next) { 

    var buf = ''; 
    // Need to accumulate all the bytes... <--- HOW TO DO THIS? 

    // then calculate HMAC-SHA1 on the content. 
    var hmac = crypto.createHmac('sha1', app.get('client_secret')); 
    hmac.update(buf); 
    var providedSignature = req.headers['X-Hub-Signature']; 
    var calculatedSignature = 'sha1=' + hmac.digest(encoding='hex'); 
    if (providedSignature != calculatedSignature) { 
     console.log(providedSignature); 
     console.log(calculatedSignature); 
     res.send("ERROR"); 
     return; 
    } 
    next(); 
}; 

app.use(sigVerifier); 
app.use(express.json()); 

回答

1

Express將connect的中間件用於json。 您可以將選項對象傳遞給json主體解析器,以在繼續解析之前驗證內容。

function verifyHmac(req, res, buf) { 
    // then calculate HMAC-SHA1 on the content. 
    var hmac = crypto.createHmac('sha1', app.get('client_secret')); 
    hmac.update(buf); 
    var providedSignature = req.headers['X-Hub-Signature']; 
    var calculatedSignature = 'sha1=' + hmac.digest(encoding='hex'); 
    if (providedSignature != calculatedSignature) { 
    console.log(
     "Wrong signature - providedSignature: %s, calculatedSignature: %s", 
     providedSignature, 
     calculatedSignature); 
    var error = { status: 400, body: "Wrong signature" }; 
    throw error; 
    } 
} 

app.use(express.json({verify: verifyHmac}));