0%

Jwt了解

Jwt了解

JWT

官网:https://jwt.io/introduction/

参考:https://www.liqingbo.cn/docs/jwt/content/summary.html

客户端与服务端之间验证的一种技术,取代了之前使用的Session

Session存在的问题

  • Session不利于搭建服务器的集群(也就是必须访问原本的那个服务器才能获取对应的SessionId)

  • CSRF: 因为是基于cookie来进行用户识别的, cookie如果被截获,用户就会很容易受到跨站请求伪造的攻击。

鉴权机制

基于token的鉴权机制类似于http协议也是无状态的,不需要去考虑用户在哪一台服务器登录

流程

  • 用户使用用户名密码来请求服务器
  • 服务器进行验证用户的信息
  • 服务器通过验证发送给用户一个token
  • 客户端存储token,并在每次请求时附送上这个token值
  • 服务端验证token值,并返回数据

token必须要在每次请求时传递给服务端,它应该保存在请求头里。

服务端要支持CORS(跨来源资源共享)策略,后端设置Access-Control-Allow-Origin: *

JWT structure(构成)

header.payload.signature

xxxxx.yyyyy.zzzzz

存储两个变量

  1. token type,token类型一般是JWT

  2. signing algorithm,签名算法,例如:HMAC SHA256 or RSA

    example:

    1
    2
    3
    4
    {
    "alg": "HS256",
    "typ": "JWT"
    }

对其进行Base64Url 编码,生成header.

1
2
# 上例Base64Url编码后的内容
ewogICJhbGciOiAiSFMyNTYiLAogICJ0eXAiOiAiSldUIgp9

payload

three parts:registered, public, and private claims.

  • registered claims 标准中注册的声明 (非强制)
    • iss:jwt签发者
    • exp:jwt的过期时间
    • sub:jwt面向的用户
    • aud:接收jwt的一方
    • nbf:该时间之前,jwt不可用
    • iat:jwt的签发时间
    • jti:jwt的唯一标识
  • public claims 公共的声明
  • private claims 私有的声明,除了registered、public

example:

1
2
3
4
5
{
"sub": "1234567890",//registered claims
"name": "John Doe",
"admin": true
}

对其进行Base64Url 编码,生成payload.

1
2
# 上例Base64Url编码后的内容
ewogICJzdWIiOiAiMTIzNDU2Nzg5MCIsLy9yZWdpc3RlcmVkIGNsYWltcyAKICAibmFtZSI6ICJKb2huIERvZSIsCiAgImFkbWluIjogdHJ1ZQp9

signature

使用 secret 和报头指定的算法对header 和 payload进行签名,生成signature。

为什么使用JWT

编码后的简洁性

As JSON is less verbose than XML, when it is encoded its size is also smaller, making JWT more compact than SAML. This makes JWT a good choice to be passed in HTML and HTTP environments.

安全性:

Security-wise, SWT can only be symmetrically signed by a shared secret using the HMAC algorithm. However, JWT and SAML tokens can use a public/private key pair in the form of a X.509 certificate for signing. Signing XML with XML Digital Signature without introducing obscure security holes is very difficult when compared to the simplicity of signing JSON.

解析的方便性

JSON parsers are common in most programming languages because they map directly to objects. Conversely, XML doesn’t have a natural document-to-object mapping. This makes it easier to work with JWT than SAML assertions.

服务器无关性

Regarding usage, JWT is used at Internet scale. This highlights the ease of client-side processing of the JSON Web token on multiple platforms, especially mobile.

localStorage

可以使用单个跨站点脚本窃取localStorage中的所有数据,因此建议不要在localStorage中存储敏感信息。

单个跨站点脚本也可用于将恶意数据加载到localStorage中,因此不要认为这些对象是可信的。

localStorage 和 sessionStorage 属性允许在浏览器中存储 key/value 对的数据。

localStorage 用于长久保存整个网站的数据,保存的数据没有过期时间,直到手动去删除。

localStorage 属性是只读的。

sessionStorage将数据保存在当前会话中

cookie可以使用httpOnly标志来降低这种风险。