What is JWT (JSON WEB TOKEN)

Source: Internet
Author: User

What is JWT

The JSON Web token (JWT) is a JSON-based development standard (RFC 7519) that is implemented for the delivery of claims between network application environments, which is designed to be compact and secure, especially for distributed site single-sign-on (SSO) scenarios. JWT declarations are typically used to pass authenticated user identities between identity providers and service providers, to obtain resources from a resource server, or to add additional declarative information that is necessary for other business logic, which can also be used directly for authentication or encryption.

Origin

Speaking of JWT, we should talk about the difference between token-based authentication and traditional session authentication.

The traditional session Certification

We know that the HTTP protocol itself is a stateless protocol, and this means that if the user provides our app with a username and password for user authentication, then the next request, the user will have to authenticate the user again, because according to the HTTP protocol, we do not know which user sent the request, So in order for our application to recognize which user is sending, we can only store a user login information in the server, this login information will be passed to the server in response, tell it to save as a cookie, so that the next request to send to our application, so that our British yo can recognize the request from which user , this is the traditional Sessino-based certification

But this session-based authentication makes the application inherently difficult to extend, and as no client is added, the standalone server is unable to host more users, and the problem of session-based authentication is exposed.

The problems revealed by the session authentication

Session: After each user through our application certification, our application will be on the server to make a record, so that the user next request authentication, usually the session is stored in memory, and as the number of certified users, the service side of the overhead will be significantly increased

Extensibility: After the user authentication, the service side does the authentication record, if the authentication record is saved in the memory, this means that the user next request must also request on this server, in order to obtain the authorized resources, thus in the distributed application, the response limits the load balancer the ability, Also means limiting the extensibility of the application

CSRF: Because cookies are based on user identification, if the cookie is intercepted, the user will be vulnerable to cross-site request forgery attacks.

Token-based authentication mechanism

Token-based authentication mechanism is similar to the HTTP protocol is stateless, it does not need to keep the user's authentication information or session information on the server. That means the opportunity. The application of the Tokent authentication mechanism does not need to consider which server the user is logged into, which facilitates the extension of the application.

This is the process.

    • User request server with user name password
    • Server to authenticate user information
    • The server sends a token to the user via authentication
    • The client stores tokens and attaches this token value on each request
    • The server validates the token and returns the data

This token must be sent to the server each time it is requested, it should be stored in the request header, and the server supports Cors (cross-origin resource sharing) policy, generally we can do this on the service side access-control-allow-origin:*

The composition of the JWT

JWT is made up of three parts, which form a JWT string with links to the three pieces of information text. Just like this.

Eyj0exaioijkv1qilcjhbgcioijiuzi1nij9.eyjvc2vyswqiojeymywivxnlck5hbwuioijhzg1pbij9.qjw1epd5p6p4yy2yju3-fkq28pddznqrj3esfal Qy_u

The first part we call it Head (header) The second part we call the load (payload, similar to the cargo carried on the aircraft), the third part is the visa (signature)

Header

The two-part information that JWT's head carries:

    • Claim type, here is JWT
    • An algorithm that declares encryption, usually directly using the HMAC SHA256

The complete head is like this JSON

{     'typ':'JWT',     ' ALG ':'HS256'  }

The head is then base64 encrypted (the encryption can be decrypted symmetrically), forming the first part

Eyj0exaioijkv1qilcjhbgcioijiuzi1nij9
Plyload

Loads are places where effective information is stored. The name is like a particular item on a plane that contains three pieces of information.

    • Declaration of registration in the standard
    • Public statements
    • Private claims

declarations registered in callouts (not recommended for mandatory use)

    • ISS:JWT issued by
    • SUB:JWT-oriented users
    • AUD: The party receiving the JWT
    • EXP:JWT expiration time, this expiration must be greater than the time of issue
    • NBF: Defines the time before which the JWT is not available
    • IAT:JWT Time of issue
    • JTI:JWT's unique identity, used primarily as a one-time token to avoid replay attacks

Public statements:

Public declarations can add any information, generally add the user's relevant information or other business needs of the necessary information, but do not recommend the addition of sensitive information, because the part of the client can be decrypted;

Private Claims

A private statement is a statement of the definition of a provider and a consumer function, and it is generally not recommended to store sensitive information because Base64 is symmetric and decrypted, meaning that the part of the information can be categorized as a message.

Define a payload

{  "sub""1234567890",  "  name"John Doe",   "  Admin"true}

Then encrypt it base64 to get part of the JWT

Eyjzdwiioiixmjm0nty3odkwiiwibmftzsi6ikpvag4grg9liiwiywrtaw4ionrydwv9

Signature

The third part of JWT is a visa information, which consists of three parts:

    • Header (after Base64)
    • Payload (after Base64)
    • Secred

This section requires Base64 after the encrypted header and Base64 encrypted payload use "." The connection consists of a string, which is then combined with secret encryption by means of encryption declared in the header, which then forms the third part of the JWT

var ' . ' + base64urlencode (payload); var ' Secret ' // Tjva95orm7e2cbab30rmhrhdcefxjoyzgefonfh7hgq

Use these three parts "." Connected to a complete string that makes up the final JWT:

EyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBa B30rmhrhdcefxjoyzgefonfh7hgq

Note: Secret is stored on the server side, JWT is issued on the service side, secret is used for the signing of JWT and JWT verification, so it is your service side of the private key, in any scenario should not be revealed, once the client learned this secret, That means the client can self-issue the JWT.

Application

Usually add authorization in the request head and add bearer callout:

Fetch ('api/user/1', {  headers: {    'Authorization ' '  ' + Token  }})

The server verifies the token and returns the appropriate resource if the validation passes, as is the case with the entire process.

Summarize

Advantages:

    • Because of the versatility of JSON, JWT can be supported across languages, such as c#,javascript,nodejs,php, and many other languages can be used
    • Because of the payload section, JWT can store some of the non-sensitive information necessary for other business logic on its own
    • Easy to transfer, the JWT composition is very simple, the byte occupies very small, so it is very easy to transfer
    • It doesn't need to save session information on the server, so it's easy to apply extensions

Safety-related

    • You should not store sensitive information in the payload section of the JWT, because that part is the part that the client can decrypt
    • Protect the secret private key. The private key is very important
    • If possible, use the HTTPS protocol

What is 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.