[Reprint] What is JWT - JSON WEB TOKEN

What is JWT - JSON WEB TOKEN

https://www.jianshu.com/p/576dbf44b2ae

 

What is the JWT

Json web token (JWT), is a statement in order to pass between the network application execution environment based on open standards JSON ( (RFC 7519 ). The token is designed to be compact and safe, especially for single-distributed sites sign-on (SSO) scenario .JWT statements are typically used to provide and service providers transfer between the user identity is authenticated identity information in order to obtain resources from the server, you can also add some extra other business logic that must be statement information, the token can be directly used for authentication may be encrypted.

origin

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

Traditional session authentication

We know, http protocol itself is a stateless protocol, and this means that if the user provides a user name and password to our application for user authentication, then the next time request, the user should once again perform user authentication before OK, because, according to the http protocol, we can not know which user request is sent, so in order to make our application can identify which user request is issued, the information we can store a copy of the server user login, this login information It will be passed to the browser in response, telling save it as a cookie, so that next time the application is sent to our request, so that our application will be able to identify which user requests from, and this is the traditional session-based authentication.

But this session-based authentication so that the application itself is difficult to be expanded, with the increase of users of different clients, independent of the server is unable to carry more users, but this time the problem-based session authentication application will be exposed.

Session-based authentication problems revealed

Session: Each user authentication after our application, our application on the server must do a record, to facilitate the identification of the user's next request, general session are stored in memory, and as the authenticated user increase in the cost of the server will be significantly increased.

Scalability: After user authentication, the server doing the authentication record, if authenticated records are stored in memory, then it means that the user requests the next request must also be on this server, so as to get the authorization of resources, so in a distributed application, the corresponding limits the ability of the load balancer. This also means that limits the scalability of applications.

CSRF: Because it is based on a cookie to identify the user, if the cookie is intercepted, the user could be vulnerable to cross-site request forgery attacks.

The token-based authentication mechanism

Similar to the http protocol is stateless token-based authentication mechanism, which does not require the server to retain the authentication information or session information of the user. This means that applications based on token authentication mechanism does not need to consider which server the user is logged in, which facilitated the application of the extension.

The process is this:

  • User for username and password to the server request
  • Server to verify the user's information
  • The server sends to the user by verifying a token
  • Client token memory, and each request included in this token value
  • The server authentication token, and returns the data

This token must be passed with each request to the server, it should be kept in a request in advance, in addition, the server to support the CORS(跨来源资源共享)strategy, we usually do it on the server side Access-Control-Allow-Origin: *.

So we are now back to the topic of JWT.

JWT look like?

JWT is composed of three pieces of information, use these three pieces of information text .with links constitute Jwt string. like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

JWT's constitution

The first part we call the head (header), the second part we call the load (payload, similar to items carried on the plane), and the third part is the visa (signature).

header

jwt head carries two pieces of information:

  • Declared type, here is jwt
  • Assertion of the encryption algorithm is usually used directly HMAC SHA256

Complete head like this in JSON:

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

Then the head base64-encryption (the encrypted can be decrypted symmetric), constitutes the first portion.

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9

playload

Load local storage is valid information. The name refers specifically to such goods carried on the aircraft, these effective information consists of three parts

  • Standard registration statement
  • Public Statement
  • Private statement

Standard registration statement (recommended, but not mandatory to use):

  • iss: jwt issuer
  • sub: jwt for the user
  • aud: the receiving side jwt
  • exp: jwt expiration time, the expiration date must be greater than the issue of time
  • nbf: What time is defined before the jwt are not available.
  • iat: jwt the issue of time
  • jti: jwt unique identity, is mainly used as a one-time token, in order to avoid a replay attack.

Public statement:
public declarations can add any information, general information about the user to add the necessary information or other business needs, but is not recommended for sensitive information to add, because the part of the client can decrypt.

Private statement:
Private statement is a statement providers and consumers as common definition, is generally not recommended to store sensitive information, because base64 is decrypted symmetric, meaning that some of the information may be classified as plaintext.

Define a payload:

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

Base64 then be encrypted to obtain the second portion of Jwt.

eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9

signature

The third part is a jwt visa information, this visa information consists of three parts:

  • header (after the base64)
  • payload (after the base64)
  • secret

And after base64 after the header part needs to encrypt the encrypted payload using base64 .string concatenation composition, and then by salt encryption header declared in secretcombination encryption, and the third portion constitutes the jwt.

// javascript
var encodedString = base64UrlEncode(header) + '.' + base64UrlEncode(payload); var signature = HMACSHA256(encodedString, 'secret'); // TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ 

These three parts with .a full string connected, constitutes the final jwt:

  eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Note: secret is stored on the server side, the issue generated jwt also on the server side, secret is used to authenticate the issuance and jwt of jwt, so it is your server's private key, in any scenario should not be revealed to go. Once the client has learned the secret, it means that the client can be self-signed jwt up.

How to apply

It is generally added in advance in the request Authorization, and add the Bearerlabel:

fetch('api/user/1', {
  headers: {
    'Authorization': 'Bearer ' + token
  }
})

The server verifies the token, if verified it will return the appropriate resource. The whole process is like this:

 
jwt-diagram

to sum up

advantage

  • Because of the versatility of json, so JWT can be cross-language support, like JAVA, JavaScript, NodeJS, PHP and many other languages ​​can be used.
  • Because of the payload section, so you can store some JWT other business logic necessary for non-sensitive information in itself.
  • Ease of transport, JWT configuration is very simple, small occupied bytes, so it is very easy to transport.
  • It does not require the server to save session information, so it is easy to extend the application

Safety-related

  • We should not store sensitive information in the payload section jwt, since it is part of the client can decrypt part.
  • Protect the secret private key that is very important.
  • If you can, please use the https protocol

Guess you like

Origin www.cnblogs.com/jinanxiaolaohu/p/12532401.html