The Lucid JWT (JSON Web Token)

Source: Internet
Author: User
Tags compact hmac sessions sha256 algorithm server memory csrf attack

1. JWT Introduction

The JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact (compact) and self-contained (self-contained) way to securely transfer information between parties as JSON objects. This information can be verified and trusted with a digital signature. JWT can be signed using a secret (using the HMAC algorithm) or using RSA's public/private key pair.

Although JWT can be encrypted to provide confidentiality between parties, we will focus on signed tokens. A signed token can verify the integrity of the claims it contains, while the encryption token hides claims from other parties. When a token is signed with a public/private key pair, the signature also proves that only the party holding the private key is the signer.

Let's further explain some of the concepts:

    • Compact:
      Because they are small in size, JWT can be sent through the Url,post parameter or HTTP headers. In addition, the smaller the size means the faster the transfer speed.
    • self-contained (self-contained):
      The payload (playload) contains all the necessary information about the user and avoids querying the database multiple times.
2. JWT Application Scenario
    • Authentication (authentication):
      This is the most common scenario for using JWT. Once a user logs in, each subsequent request will contain a JWT that allows the user to access the routes, services, and resources allowed by the token. Single Sign-on is a feature of today's widely used JWT because it is inexpensive and easy to use across different domains.
    • Information exchange (Information exchange):
      JSON Web tokens is a good way to securely transfer information between parties. Because JWT can be signed: for example, with a public/private key pair, you can be sure that the sender is the person they claim to be. In addition, because the signature is computed using headers and payloads, you can also verify that the content has not been tampered with.
3. JWT structure

In a compact form, the JWT consists of three parts separated by a point (.), respectively:

    • Header
    • Payload
    • Signature

The JWT structure usually looks like this:

xxxxx.yyyyy.zzzzz

Let's introduce these three sections separately:

Header

The header is usually made up of two parts: the type of token, the JWT. and common hashing algorithms, such as HMAC SHA256 or RSA.
For example:

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

The JSON in the header section is Base64url encoded to form the first part of the JWT.

Payload

There are 3 kinds of declarations (Claims) in the definition of the statement, which can be said to be the place where the communication message is stored:

    • registered claims (registration statement):
      These are a set of pre-defined declarations that are not mandatory, but are recommended to provide a useful set of interoperable declarations. Some of them are: iss (issuer), exp (expiry time), sub (subject), (audience aud ), etc. #Registered Claim names#

    • Public claims (publicly stated):
      These can be defined arbitrarily by the person using the JWT. To avoid conflicts, however, you should define them in the IANA JSON Web token registry or define them as URIs that contain conflict-prevention namespaces.
    • Private claims (privacy statement):
      These are custom statements created to agree to use them but neither register nor publicly declare the parties to share information.

The playload example is as follows:

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

The JSON of the playload part is Base64url encoded to form the second part of the JWT.

Notice:

Note that for signed tokens, this information is protected by tampering, but can be read by anyone. Do not place secret information in a valid content or header element of a JWT unless it is encrypted. This is also a lot of articles arguing about JWT security reasons, do not use JWT instead of server-side session state mechanism. For more information, please read this article: Stop Using Jwt for Sessions.

Signature

The third part signature is used to verify the identity of the sending requestor, which is formed by the first two parts.
To create the signature section, you must use the encoded header, encode the payload, the secret key, the specified algorithm in the header, and sign the signature.
For example, if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:

HMACSHA256(  base64UrlEncode(header) + "." +  base64UrlEncode(payload),  secret)
3. JWT Practice

JWT outputs three point-delimited base64-url strings that can be easily passed in HTML and HTTP environments, and is more compact than XML-based standards such as SAML.

The following JWT example, which has a previous header and payload encoding, and is signed with a secret key.

We can use the Jwt.io debugger to decode, validate, and generate JWT:

4.JWT Working principle

In authentication, when a user successfully logs on using their credentials, the JSON Web token is returned and must be kept locally (usually in local storage, but can also use cookies) instead of creating a session server in the traditional method and returning a cookie.

Security considerations must be taken into account about how tokens are stored.
Reference: #Where to Store tokens#

Whenever a user wants to access a protected route or resource, the user agent should use the hosting scenario to send a JWT, typically in a field in the request header Authorization , using the Bearer schema:

Authorization: Bearer <token>

This is a stateless authentication mechanism because the user state is never saved in server memory. A server-protected route checks for a valid JWT in the authorization header and, if present, allows the user to access the protected resource. Because JWT is independent, all the necessary information is there, reducing the need to query the database multiple times.

This allows us to rely entirely on stateless data APIs and even make requests to downstream services. No matter which domains are serving the API, there is no cross-domain resource sharing (CORS) issue because it does not use cookies.

Notice:

Note that with a signed token, all the information contained in the token is exposed to the user or other party, even if they cannot change it. In JWT, no sensitive data, such as passwords, should be added to the playload. If you put a user's password in a JWT, a malicious third party will be able to quickly know your password by Base64 decoding.

5. Frequently asked Questions ①JWT safe?

Base64 encoding method is reversible, that is, the token content issued after encoding can be parsed. In general, we do not recommend that sensitive information, such as the user's password, be placed within the payload.

Can ②JWT Payload be forged?

One of the components of the JWT is signature, which prevents the payload content from being pushed back through the Base64 reversible method and modifying it. Because signature is made up of Base64 together with payload through the header.

③ if my Cookie is stolen, does that mean that a third party can do a CSRF attack?

Yes, a cookie is lost, which means that identity can be forged. Therefore, the official recommendation is to be used in the localstorage, and placed in the request header to send.

④ space and length issues?

JWT tokens are usually not too small in length, especially stateless JWT tokens, which put all the data in tokens and quickly exceed the size of the cookie (4K) or the URL length limit.

⑤token failure problem?
      1. After the stateless JWT token (stateless JWT token) is released, the token cannot be invalidated by the server side and must wait until the expiration time expires before it loses its usefulness.
      1. It is assumed that token is intercepted between the two, or that there is a change in the authority to manage identities, and that the authorization scope modification cannot prevent the token invalidation from being issued and require the user to re-request the new token.
6. JWT Usage Recommendations
    • Do not store sensitive information in tokens.
    • The time limit in payload is exp not set too long.
    • Turn on Only Http prevent XSS attacks.
    • If you are concerned about replay attacks (replay attacks) can be increased jti (JWT ID), exp (valid time) Claim.
    • Add the blacklist mechanism to your application layer and block it if necessary (this is a manual defense against the token being stolen by a third party).

[1] Stop using JWT for sessions:
http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/
[3] Use JWT the right way!:
Https://stormpath.com/blog/jwt-the-right-way
[2] JSON Web Token Wikipedia:
Https://en.wikipedia.org/wiki/JSON_Web_Token

In-depth JWT (JSON Web Token)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.