jiansoung / issues-list

记录日常学习和开发遇到的问题。欢迎评论交流:)
https://github.com/jiansoung/issues-list/issues
MIT License
14 stars 0 forks source link

Notes on JSON Web Token #8

Open jiansoung opened 6 years ago

jiansoung commented 6 years ago

Notes on JSON Web Token

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.

When should you use JSON Web Tokens?

What is the JSON Web Token structure?

<Header>.<Payload>.<Signature>

Header

The header is a JSON object, and is Base64Url encoded, typically consists of two parts:

Payload

The payload (JSON object) contains the claims, which are statements about an entity (typically, the user) and additional data. And also be Base64Url encoded.

Types of claims:

Do not put secret information in the payload or header elements of a JWT unless it is encrypted.

Signature

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.

Create signature with the HMAC SHA256 algorithm:

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

The signature is used to verify the message wasn't changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.

How do JSON Web Tokens work?

Typically client sends the JWT in the Authorization header using the Bearer schema.

Authorization: Bearer <token>

This can be, in certain cases, a stateless authorization mechanism.

If the token is sent in the Authorization header, Cross-Origin Resource Sharing (CORS) won't be an issue as it doesn't use cookies.

References