Home > Backend Development > Python Tutorial > Introduction to JWT principles and simple applications (with code)

Introduction to JWT principles and simple applications (with code)

不言
Release: 2019-03-29 10:53:39
forward
2967 people have browsed it

This article brings you an introduction to JWT principles and simple applications (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

JWT authentication login

Recently I am working on an audit system. JWT login authentication is used for background login. Here I will mainly make a summary

What is JWT

Json web token (JWT), according to the official website's definition, is a JSON-based open standard implemented to transfer claims between network application environments. The token is designed to be compact and secure, especially suitable for distributed sites Single sign-on scenario. JWT claims are generally used to transfer authenticated user identity information between identity providers and service providers in order to obtain resources from the resource server. Some additional claim information necessary for other business logic can also be added. The token is also It can be used directly for authentication or encrypted.

Why use JWT

This is mainly compared with the traditional session. The traditional session needs to save some login information on the server side, usually in memory, and the back-end server is a cluster, etc. In a distributed situation, other hosts do not save this information, so they need to be verified through a fixed host. If the number of users is large, it is easy to form a bottleneck at the authentication point, making the application difficult to expand.

JWT Principle

JWT consists of three parts, separated by dots. It looks like this. The JWT token itself has no spaces, line breaks, etc. The following is processed for the sake of appearance

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.
eyJpc3MiOiJsYWJzX3B1cmlmaWVyLWFwaS1wYW5lbCIsImlhdCI6MTU1Mjk3NTg3OCwiZXhwIjoxNTU1NTY3ODc4LCJhdWQiOiJodHRwOi8vZmYtbGFic19wdXJpZmllci1hcGktdGVzdC5mZW5kYS5pby9wcm9kL3YxL2F1dGgvand0Iiwic3ViIjoiMTUwMTM4NTYxMTg4NDcwNCIsInNjb3BlcyI6WyJyZWdpc3RlciIsIm9wZW4iLCJsb2dpbiIsInBhbmVsIl19.
m0HD1SUd30TWKuDQImwjIl9a-oWJreG7tKVzuGVh7e4
Copy after login
1. Header

Header part is a json, describing the metadata of JWT, usually as follows

{
  "alg": "HS256",
  "typ": "JWT"
}
Copy after login

alg indicates the algorithm used for signature, the default is HMAC SHA256, written as HS256, tye represents the type of this token, JWT token uses JWT uniformly, the token generated by the above header is

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
Copy after login
2. Payload

Officially stipulates 7 fields, explained as follows

  • iss: The issuer can fill in the ID to generate this token, etc. Optional parameter
  • sub: The customer for which the JWT is oriented, can store the user account_id, etc., optional
  • aud: The receiver of the JWTtoken can fill in the interface URL that generates this token, but it is not mandatory, optional
  • exp: expiration time, timestamp, Integer, optional parameters
  • iat: the time when the token was generated, unix time, timestamp, optional parameters
  • nbf (Not Before): indicates that the token is not available before this time, verification It means not passing, optional
  • jti: JWT ID, mainly used to generate one-time token, optional parameters

In addition to the official, we can also define some custom Define fields, but consider that BASE64 is reversible, so do not put sensitive information
The following is an example;

{
  "iss": "labs_purifier-api-panel",
  "iat": 1552975878,
  "exp": 1555567878,
  "aud": "http://ff-labs_purifier-api-test.fenda.io/prod/v1/auth/jwt",
  "sub": "1501385611884704",
  "scopes": [
    "register",
    "open",
    "login",
    "panel"
  ]
}
Copy after login

The above Payload, after BASE64 encryption, the generated token is

eyJpc3MiOiJsYWJzX3B1cmlmaWVyLWFwaS1wYW5lbCIsImlhdCI6MTU1Mjk3NTg3OCwiZXhwIjoxNTU1NTY3ODc4LCJhdWQiOiJodHRwOi8vZmYtbGFic19wdXJpZmllci1hcGktdGVzdC5mZW5kYS5pby9wcm9kL3YxL2F1dGgvand0Iiwic3ViIjoiMTUwMTM4NTYxMTg4NDcwNCIsInNjb3BlcyI6WyJyZWdpc3RlciIsIm9wZW4iLCJsb2dpbiIsInBhbmVsIl19
Copy after login
3.Signature(Signature)

Signature is the encryption of the two tokens generated in the previous two parts. The encryption method used is specified in the Header. Here it is HS256. At this time, a secret key is required. , cannot be leaked, the general process is as follows:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)
Copy after login

Use of JWT

JWT token is generally placed in the request header, of course it can also be placed in the cookie, but it cannot be placed in the cookie across Domain, for example:

Authorization: Bearer <token>
Copy after login

Simple generation and verification of JWT in Python

jwt library

Generate token

def create_token():
    payload={
              "iss": "labs_purifier-api-panel",
              "iat": 1552975878,
              "exp": 1555567878,
              "aud": Config.AUDIENCE,
              "sub": "1501385611884704",
              "scopes": [
                "register",
                "open",
                "login",
                "panel"
              ]
            }
    token = jwt.encode(payload, Config.SECRET_KEY, algorithm='HS256')
    return True, {'access_token': token}
Copy after login

Verify token

def verify_jwt_token(token):
    try:
        payload = jwt.decode(token, Config.SECRET_KEY,
                             audience=Config.AUDIENCE,
                             algorithms=['HS256'])
    except (ExpiredSignatureError, DecodeError):
        return False, token
    if payload:
        return True, jwt_model
Copy after login

It should be noted that if the aud parameter is added when generating, the audience parameter must also be used during verification, and the values ​​must be the same

This article has ended here. For more other exciting content, you can pay attention to the python video tutorial column on the PHP Chinese website!

The above is the detailed content of Introduction to JWT principles and simple applications (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template