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
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
Officially stipulates 7 fields, explained as follows
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
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)
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>
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!