


Introduction to JWT principles and simple applications (with code)
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
1. Header
Header part is a json, describing the metadata of JWT, usually as follows
{ "alg": "HS256", "typ": "JWT" }
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
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" ] }
The above Payload, after BASE64 encryption, the generated token is
eyJpc3MiOiJsYWJzX3B1cmlmaWVyLWFwaS1wYW5lbCIsImlhdCI6MTU1Mjk3NTg3OCwiZXhwIjoxNTU1NTY3ODc4LCJhdWQiOiJodHRwOi8vZmYtbGFic19wdXJpZmllci1hcGktdGVzdC5mZW5kYS5pby9wcm9kL3YxL2F1dGgvand0Iiwic3ViIjoiMTUwMTM4NTYxMTg4NDcwNCIsInNjb3BlcyI6WyJyZWdpc3RlciIsIm9wZW4iLCJsb2dpbiIsInBhbmVsIl19
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)
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>
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}
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
