Understanding JWT (JSON Web Token) authentication

Source: Internet
Author: User
Tags oauth

Understanding JWT (JSON Web Token) authentication

Recently want to make a small program, need to use the authorization certification process. Previous projects are used OAUTH2 certification, but sanic use OAuth2 is not very convenient, you want to try a JWT certification method. The main content of this article is the certification principle of JWT, and the practice that Python recognizes with JWT.

Several common authentication mechanisms HTTP Basic Auth

HTTP Basic AuthIn HTTP, Basic authentication is a form of login authentication that allows a Web browser or other client program to provide credentials in the form of a user name and password when requested, usually with the user name and plaintext passed through the HTTP header.

Before sending, a colon is appended with the user name and then the password is threaded, and the resulting string is then encoded with the BASE64 algorithm. For example, the user name provided is Aladdin, password is open sesame, then the result of stitching is aladdin:open sesame, and then use it Base64编码 , get qwxhzgrpbjpvcgvuihnlc2ftzq==. The BASE64 encoded string is eventually sent out, and the recipient decodes a string of user names and passwords separated by colons.

优点

One advantage of Basic authentication is that basically all popular web browsers support Basic authentication.

缺点

Since the user name and password are BASE64 encoded, and the BASE64 encoding is reversible, the user name and password can be considered plaintext. Therefore, only if the connection between the client and the server host is secure and trustworthy, it can be used.

Next we look at a more secure and more applicable range of authentication methods OAuth .

Oauth

OAuth is an open network standard for authorization (authorization). Allows users to provide a token instead of a user name and password to access their data stored in a particular service provider. The current version is 2.0.

Strictly speaking, OAuth2 is not a standard protocol, but a secure authorization framework. It describes in detail the different roles, users, service front-end applications (such as APIs) in the system, and how mutual authentication is achieved between the client (such as a Web site or mobile app).

noun definitions
    • Third-party Application: Third-party applications, also known as "clients" (client)

    • HTTP Service:http Service Provider

    • Resource owner: The resource owner, typically referred to as the user.

    • User agent: A browser, for example.

    • Authorization server: The server that the service provider is dedicated to handle authentication.

    • Resource Server: A resource server, which is a server where a service provider holds user-generated resources. It can be the same server as the authentication server, or it can be a different server.

OAuth 2.0 Run Process

(A) After the user opens the client, the client asks the user to grant authorization.
(B) The user agrees to grant the client authorization.
(C) The client uses the authorization obtained in the previous step to request a token from the authentication server.
(D) After the authentication server authenticates the client, it confirms the error and agrees to issue the token.
(E) The client uses a token to request a resource from the resource server.
(F) The resource server confirms that the token is correct and agrees to open the resource to the client.

优点

Rapid development
Small amount of code implemented
Reduction in maintenance work
Using OAuth2 is a good choice when designing APIs to be used by different apps, and each app is used differently.

缺点
OAuth2 is a security framework that describes licensing issues across multiple applications in various scenarios. There is a huge amount of information to learn and it takes a lot of time to fully understand it.
OAuth2 is not a strict standard protocol, so it is more prone to error during implementation.

After understanding the above two ways, now finally to the focus of this article, JWT certification.

JWT Certification

Json web token (JWT), based on the definition of the official website, is a JSON-based open standard (RFC 7519) that executes in order to pass claims across a network application environment. The token is designed to be compact and secure, especially for single sign-on (SSO) scenarios in distributed sites. 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.

JWT Features
    • Small size and fast transfer speed

    • Various transmission modes, can be transmitted by Url/post parameters/http Head etc.

    • Strictly structured. It itself (in payload) contains all the user-related authentication messages, such as user-accessible routing, access validity, and other information, the server no longer has to connect to the database to verify the validity of the information, and payload support for your app is customized.

    • Supports cross-domain authentication and can be applied to single sign-on.

JWT principle

JWT is a scenario that Auth0 proposes to implement authorization validation by encrypting the JSON signature, and the encoded JWT looks like a string of characters:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

.It is divided into three segments, which can be obtained by decoding:

1. Head (header) // 包括类别(typ)、加密算法(alg);

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

The head of the JWT contains two pieces of information:

    • Claim type, here is JWT

    • An algorithm that declares encryption is usually used directly with the HMAC SHA256

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

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ92. Load (payload)

Loads are places where effective information is stored. These valid information consists of three parts:

    • Registration statement in standard

    • A public reputation

    • Private claims

公共的声明 :
Public declarations can add any information, generally add information about the user or other necessary information for business needs. However, it is not recommended to add sensitive information because the part is decrypted on the client.

私有的声明 :
A private statement is a statement that is defined by both the provider and the consumer, and is generally not recommended for storing sensitive information, because Base64 is symmetric and decrypted, meaning that the part of the information can be classified as plaintext information.

Here is an example:

// 包括需要传递的用户信息;

  "iss": "Online JWT Builder",
  "iat": 1416797419,
  "exp": 1448333419,
  "aud": "www.gusibi.com",
  "sub": "uid",
  "nickname": "goodspeed",
  "username": "goodspeed",
  "scopes": [ "admin", "user" ] 
}
    • ISS: The issuer of the JWT, whether the use is optional;

    • Sub: The user to which the JWT is intended to use is optional;

    • AUD: Whether the party receiving the JWT is used is optional;

    • EXP (expires): When expires, here is a Unix timestamp, whether the use is optional;

    • IAT (issued at): When issued (Unix time), whether the use is optional;

Others are:

    • NBF (not before): If the current time is before the time in NBF, then token is not accepted, usually leaving some leeway, such as a few minutes, whether the use is optional;

    • JTI:JWT's unique identity is used primarily as a one-time token to avoid replay attacks.

The above JSON object can be used to base64编码 get the following string. This string we call it the payload (load) of the JWT.

eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE0MTY3OTc0MTksImV4cCI6MTQ0ODMzMzQxOSwiYXVkIjoid3d3Lmd1c2liaS5jb20iLCJzdWIiOiIwMTIzNDU2Nzg5Iiwibmlja25hbWUiOiJnb29kc3BlZWQiLCJ1c2VybmFtZSI6Imdvb2RzcGVlZCIsInNjb3BlcyI6WyJhZG1pbiIsInVzZXIiXX0

信息会暴露: Because the reversible base64 encoding is used here, the second part of the data is actually clear text. We should avoid storing private information that is not publicly available here.

3. Signature (signature) // 根据alg算法与私有秘钥进行加密得到的签名字串;// 这一段是最重要的敏感信息,只能在服务端解密;
HMACSHA256( 
   base64UrlEncode(header) + "." + 
   base64UrlEncode(payload), 
   SECREATE_KEY
)

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

    • Header (after Base64)

    • Payload (after Base64)

    • Secret

Use a period for the two encoded strings above. Connected together (head in front), formed:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJKb2huIFd1IEpXVCIsImlhdCI6MTQ0MTU5MzUwMiwiZXhwIjoxNDQxNTk0NzIyLCJhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLCJzdWIiOiJqcm9ja2V0QGV4YW1wbGUuY29tIiwiZnJvbV91c2VyIjoiQiIsInRhcmdldF91c2VyIjoiQSJ9

Finally, we encrypt the string above the concatenation with the HS256 algorithm. In the encryption, we also need to provide a key (secret). If we use it secret as a key, then we can get our encrypted content:

pq5IDv-yaktw6XEa5GEv07SzS9ehe6AcVSdTj0Ini4o

Use these three parts. Connect to a complete string that forms the final JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE0MTY3OTc0MTksImV4cCI6MTQ0ODMzMzQxOSwiYXVkIjoid3d3Lmd1c2liaS5jb20iLCJzdWIiOiIwMTIzNDU2Nzg5Iiwibmlja25hbWUiOiJnb29kc3BlZWQiLCJ1c2VybmFtZSI6Imdvb2RzcGVlZCIsInNjb3BlcyI6WyJhZG1pbiIsInVzZXIiXX0.pq5IDv-yaktw6XEa5GEv07SzS9ehe6AcVSdTj0Ini4o

签名的目的: The signature is actually the signature of the header and the payload content. Therefore, if someone modifies the contents of the head and the payload and then encodes it, then the signature of the new head and payload will be different from the previous signature. Also, if you do not know the server encryption when using the key, the signature will certainly be different.
This will ensure that tokens are not tampered with.

After token is generated, you can then use token to communicate with the server.

Is the client using JWT to interact with the server process:

Here in the third step after we get the JWT, we need to store the JWT in the client, and then each request for authentication needs to send the JWT over. (Can be placed on the Authorization of the header when requested)

JWT Usage Scenarios

The main advantage of JWT is that it handles user sessions in an app in a stateless, extensible way. The server can easily get the user's session information through the embedded declarative information, without having to access the user or session database. This is useful in a distributed service-oriented framework.

However, if the system needs to use the blacklist to achieve a long-term effective token refresh mechanism, this stateless advantage is not obvious.

优点

Rapid development
No Cookies required
The wide application of JSON on the mobile side
Do not rely on social login
A relatively simple conceptual understanding

缺点

Token has a length limit
Token cannot be revoked
Token required with expiry time limit (exp)

Understanding JWT (JSON Web Token) authentication

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.