Json Web Token (JWT), as defined on the website, is a JSON-based open standard for passing declarations between network application environments (RFC 7519). The token is designed to be compact and secure, particularly suitable for single sign-on (SSO) scenarios with distributed sites. JWT declarations are generally used to pass authenticated user identity information between the identity provider and the service provider in order to obtain resources from the resource server. They can also add some additional declaration information required by other business logic. The token can also be directly used for authentication or encryption. For more information, see this article to understand JWT (JSON Web Token) authentication and practices
JWT characteristics
advantages
- Small size, so the transmission speed is fast
- There are various transmission modes, such as URL, POST parameter, and HTTP header
- Strict structuring. The payload itself (in payload) contains all the user-related validation messages, such as the route the user can access, the validity period of the access, and so on. The server does not need to connect to the database to verify the validity of the information, and the payload can be customized for your application.
- Cross-domain authentication is supported and can be applied to single sign-on.
Existing problems
The JWT itself (in Payload) contains all user-related validation messages, so it is usually not necessary to save them. There are several problems with this design:
- The Token cannot be revoked — the previous JWT can still be used after the client resets the password (JWT is not expired or invalid)
- Refresh token is not supported, and the complete process of login authorization needs to be performed after JWT expires
- There is no way to know how many JWT the user has signed
Possible solutions to the first problem are:
- Save the JWT to the database (or Redis) so that it can be checked individually for each JWT
- When all JWT such as password reset need to be invalidated, the operation time point is recorded to the database (or Redis). During JWT verification, it is also determined whether there has been any similar operations such as password reset after the creation of the JWT. If the verification fails
Of course, with this solution, there will be one more database request, which reduces the advantage of JWT being able to verify itself, and also affects authentication efficiency.
This article focuses on ideas for solving the second problem, which does not support Refresh Tokens.
refresh token
Refresh Token is a concept in OAuth2 authentication. Generated together with the Access token of OAuth2, it indicates that the refresh token is updated. The expiration time is longer than that of the Access token and can be used to obtain the next access token.
If JWT needs to add refresh token support, the following conditions must be met for refresh token:
- Generated with JWT and returned to the client
- The effective time is longer than JWT
- It can only be used in exchange for the next JWT, not for access authentication
- Not reusable (optional)
Refresh Token obtaining process
Refresh Token usage process
Code sample
import jwt
import time
Use SANic as a restful API framework
def create_token(account_id, username):
payload = {
"iss": "gusibi.mobi"."iat": int(time.time()),
"exp": int(time.time()) + 86400 * 7."aud": "www.gusibi.mobi"."sub": account_id,
"username": username,
"scopes": ['open']
}
token = jwt.encode(payload, 'secret', algorithm='HS256')
payload['grant_type'] = "refresh"
refresh_token = jwt.encode(payload, 'secret', algorithm='HS256')
return True, {
'access_token': token,
'account_id': account_id,
"refresh_token": refresh_token
}
# Verify whether refresh Token is valid
def verify_refresh_token(token):
payload = jwt.decode(token, 'secret', audience='www.gusibi.com', algorithms=['HS256'])
Check whether the token is valid and whether it is a refresh token. After verification, new tokens and refresh_token are generated
if payload and payload.get('grant_type') = ='refresh':
If you want to use the token, you need to use redis or database (redis recommended).
return True, payload
return False.None
# Verify whether the token is valid
def verify_bearer_token(token):
If the aud parameter is used to generate the token, then add this parameter to the verification
payload = jwt.decode(token, 'secret', audience='www.gusibi.com', algorithms=['HS256'])
# Verify whether the token is valid and cannot be a refresh token
if payload and not payload.get('grant_type') = ='refresh':
return True, payload
return False.None
Copy the code
Refer to the link
- Understand JWT (JSON Web Token) authentication and practices
- Understand the 2.0 [1]
The References [1] to understand the 2.0: www.ruanyifeng.com/blog/2014/0…
Finally, thank my girlfriend for her support and tolerance, more than ❤️
Around the male can also enter the keywords for historical article: male number & small program | | concurrent design mode & coroutines