十分钟快速入门JWT

2017-04-14  本文已影响381人  FX_SKY

JWT 即 JSON Web Token,是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.

JWT应用场景

Here are some scenarios where JSON Web Tokens are useful:

  • Authentication: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.

  • Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties, because as they can be signed, for example using public/private key pairs, you can be sure that the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.

JWT的组成

JSON Web Tokens 由三部分组成:

JWT由上述三段信息构成的,将这三段信息文本用.链接一起就构成了JWT字符串,如下:
xxxxx.yyyyy.zzzzz

Header

JWT的头部由两部分信息组成:

完整的头部就像下面这样的JSON:

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

载荷就是存放有效信息的地方,这些有效信息包含三个部分:

一个payload示例如下:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

Signature

JWT的第三个部分签名 需要将base64UrlEncode(header) 和base64UrlEncode(payload)使用.连接组成的字符串,然后通过header中声明的加密方式进行加盐secret组合加密,原文如下:

To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and > > sign that.

例如,使用HMAC SHA256,Signature计算如下:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

将这三部分用.连接成一个完整的字符串,构成了最终的JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.
TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

secret是保存在服务器端的,JWT是由服务器端生成并返回给客户端的,secret就是用来进行JWT的签发和JWT的验证,所以,它就是你服务端的私钥,在任何场景都不应该流露出去。

JWT如何工作的

一般是在请求头里加入Authorization,并加上Bearer标注:

Authorization: Bearer <token>

服务端校验token的合法性,如果验证通过就会返回相应的资源。整个流程就是这样的:

jwt-diagram.png

参考资料

https://jwt.io/introduction/

上一篇下一篇

猜你喜欢

热点阅读