首先pip install jwt
数据加密-sha1
import hashlib pwd='123456' hash_pwd=hashlib.sha1(pwd.encode()).hexdigest() print(hash_pwd)
hash加盐加密
from werkzeug.security import generate_password_hash,check_password_hash pwd='123456' #加盐加密,三部分组成,每次加密的结果是随机的 hash_pwd=generate_password_hash(pwd,method='pbkdf2:sha1:200',salt_length=8) print(len(hash_pwd)) print(hash_pwd) #验证密文 res=check_password_hash(hash_pwd,pwd) print(res)#密码正确返回True
- token:令牌。存储在客户端,用来验证用户信息
1.用户使用用户名密码请求服务器
2.服务器进行验证用户信息
3.服务器通过验证发送给用户一个token
4.客户端存储token,并在每次请求时附加这个token值
5.服务器验证token,并返回数据 这个token必须要在每次请求时发送给服务器,它应该保存在请求头中,另外,服务器要支持CORS(跨来源资源共享)策略,一般我们在服务端这么做就可以了 Access-Control-Allow-Origin:*
发送令牌
```
import jwt
from datetime import datetime,timedelta
def send_token(id):
datetimeInt=datetime.now+timedelta(seconds=180)
SECRET_KEY='123456'
option={
'iss':'jobapp.com',#签发者
'exp':datetimeInt,#过期时间
'aud':'webkit',#token的接受者,这里指定为浏览器
'user_id':id #放入用户信息,唯一标识
}
token=jwt.encode(option,SECRET_KEY,'HS256').decode()
return token
```
验证令牌
```
def check_token(token):
decoded=jwt.decode(token,'123456',audience='webkit',algorithms=['HS256'])
return decode
```