1. Preamble
Recently in doing weibo public number development in the web authorization, weibo need the user themselves in the authorization url with a token-like state parameters to prevent cross-site attacks.
After much thought, I've tried to implement a scheme for generating and validating tokens. I'll post the code next. I hope readers will guide me.
2、Generate token
Principle:
The hmac sha1 algorithm generates a message digest of the user's key and the maximum expiration timestamp of the token, which is spliced with the maximum expiration timestamp via ":", and then encoded in base64 to generate the final token.
Realization:
import time import base64 import hmac def generate_token(key, expire=3600): r''' @Args. key: str (user given key, need to be saved by the user to verify the token later, each time the token is generated the key can be the same key) expire: int (maximum time in s) @Return. state: str ''' ts_str = str(() + expire) ts_byte = ts_str.encode("utf-8") sha1_tshexstr = (("utf-8"),ts_byte,'sha1').hexdigest() token = ts_str+':'+sha1_tshexstr b64_token = base64.urlsafe_b64encode(("utf-8")) return b64_token.decode("utf-8")
3、Verify the token
Principle:
Decode the token in base64, get the maximum expiration timestamp of the token and the message digest from the token. Determine whether the token is expired or not.
If it does not expire, then the maximum expiration timestamp will be obtained from the token for the hmac sha1 algorithm (note that the key here should be the same as the key used to generate the token), and finally the resulting digest will be compared with the message digest obtained from the token, if the two digests are equal, the token is valid, otherwise the token is invalid.
Realization:
import time import base64 import hmac def certify_token(key, token): r''' @Args: key: str token: str @Returns: boolean ''' token_str = base64.urlsafe_b64decode(state).decode('utf-8') token_list = token_str.split(':') if len(token_list) != 2: return False ts_str = token_list[0] if float(ts_str) < (): # token expired return False known_sha1_tsstr = token_list[1] sha1 = (("utf-8"),ts_str.encode('utf-8'),'sha1') calc_sha1_tsstr = () if calc_sha1_tsstr != known_sha1_tsstr: # token certification failed return False # token certification success return True
4. Usage
key = "JD98Dskw=23njQndW9D" # Expires in an hour token = generate_token(key, 3600) certify_token(key, token)
5、Note!!!
This code can only be run in.
The above this python generate token and token validation method is all that I have shared with you, I hope to give you a reference, and I hope you support me more.