微信token认证方法原理

 1 var http = require('http');
 2 var url = require("url");
 3 var crypto = require("crypto");
 4 var port = 18080;
 5 
 6 function sha1(str){
 7     var md5sum = crypto.createHash("sha1");
 8     md5sum.update(str);
 9     str = md5sum.digest("hex");
10     return str;
11 }
12 
13 function validateToken(req,res){
14     var query = url.parse(req.url,true).query;
15     //console.log("*** URL:" + req.url);
16     //console.log(query);
17     var signature = query.signature;
18     var echostr = query.echostr;
19     var timestamp = query['timestamp'];
20     var nonce = query.nonce;
21     var oriArray = new Array();
22     oriArray[0] = nonce;
23     oriArray[1] = timestamp;
24     oriArray[2] = "token";//这里是你在微信开发者中心页面里填的token,而不是****
25     oriArray.sort();
26     var original = oriArray.join('');
27     console.log("Original str : " + original);
28     console.log("Signature : " + signature );
29     var scyptoString = sha1(original);
30     if(signature == scyptoString){
31         res.end(echostr);
32         console.log("Confirm and send echo back");
33     }else {
34         res.end("false");
35         console.log("Failed!");
36     }
37 }
38 
39 
40 var webSvr = http.createServer(validateToken);
41 webSvr.listen(port,function(){
42     console.log("Start validate");
43 });

与PHP的源码有异曲同工之处;

 1 private function checkSignature()
 2 {
 3         $signature = $_GET["signature"];
 4         $timestamp = $_GET["timestamp"];
 5         $nonce = $_GET["nonce"];    
 6                 
 7     $token = TOKEN;
 8     $tmpArr = array($token, $timestamp, $nonce);
 9     sort($tmpArr, SORT_STRING);
10     $tmpStr = implode( $tmpArr );
11     $tmpStr = sha1( $tmpStr );
12     
13     if( $tmpStr == $signature ){
14         return true;
15     }else{
16         return false;
17     }
18 }

再看小新写的nodejs版本;

 1 var http = require('http');
 2 var crypto = require('crypto');
 3  
 4 var server = http.createServer(); 
 5    
 6 server.on('request',function (req, res){ 
 7   res.writeHead(200, {'Content-Type': 'text/plain'}); 
 8    
 9   var signature = require('url').parse(req.url,true).query.signature
10   var timestamp = require('url').parse(req.url,true).query.timestamp
11   var echostr = require('url').parse(req.url,true).query.echostr
12   var nonce = require('url').parse(req.url,true).query.nonce
13   var token = 'Token';
14   var tmpArr = Array(token, timestamp, nonce).sort().join("");
15   var sha1 = crypto.createHash('sha1');
16   sha1.update(tmpArr);
17   tmpArr = sha1.digest('hex');
18   if(tmpArr == signature){
19     res.end(echostr);  
20   }else{
21     res.end('404');
22   }
23    
24 }); 
25  
26 server.listen(8088);

大体思路就是接受微信服务器发来的请求;

拆分参数;将参数排序、拼接、加密,与参数其中之一比对;

成功返回其中参数之一;

失败false;

posted @ 2016-03-28 18:34  挥刀  阅读(2891)  评论(0编辑  收藏  举报