json web token

2016-08-12  本文已影响0人  wmtcore

由来

JWT介绍

// 1. Headers
// 包括类别(typ)、加密算法(alg);
{
  "alg": "HS256",
  "typ": "JWT"
}
// 2. Claims
// 包括需要传递的用户信息;
{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}
// 3. Signature
// 根据alg算法与私有秘钥进行加密得到的签名字串;
// 这一段是最重要的敏感信息,只能在服务端解密;
HMACSHA256(  
    base64UrlEncode(header) + "." +
    base64UrlEncode(payload),
    SECREATE_KEY
)

在使用过程中,服务端通过用户登录验证之后,将Header+Claim信息加密后得到第三段签名,然后将三段签名合并后返回给客户端。客户端获取到token后,应该在每次向服务器请求数据时附带这个token,然后服务端验证token。

client

encoded

jwt.sign(payload, secretOrPrivateKey, options, [callback]);

payload Claims,即传递的用户信息,could be an object literal, buffer or string.if not,it will be coerced into a string using JSON.stringify.

secretOrPrivateKey is a string or buffer containing either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA.字符串,或着fs.readFileSync读取的证书

options:

Example

// sign with default (HMAC SHA256)
var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'shhhhh');

// sign with RSA SHA256
var cert = fs.readFileSync('private.key');  // get private key
var token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'});

decoded

var jwt = require('express-jwt');

app.get('/protected',
  jwt({secret: 'shhhhhhared-secret'}),
  function(req, res) {
    if (!req.user.admin) return res.sendStatus(401);
    res.sendStatus(200);            
  });

you can make some paths unprotected as follows:

//设置路由/token 不验证
app.use(jwt({ secret: 'shhhhhhared-secret'}).unless({path: ['/token']}));

By default, the decoded token is attached to req.user but can be configured with the requestProperty option.
默认解密后的token Claim内容加到req.user

//将解密后的token加到req.auth
jwt({ secret: publicKey, requestProperty: 'auth' });

安全性

上一篇 下一篇

猜你喜欢

热点阅读