安装pyjwt:pip install pyjwt
pyjwt的使用,主要是一个加密,一个解密
token校验代码
在视图中使用
1、登录,获取token
2、用token请求需校验token的接口
auth:
from functools import wraps
import jwt
from sanic import text
def check_token(request):
""" 校验token是否有效 """
try:
jwt.decode(request.headers.get('token'), request.app.config.SECRET, algorithms=["HS256"])
except jwt.exceptions.InvalidTokenError:
return False
else:
return True
def login_required(wrapped):
""" token校验装饰器 """
def decorator(f):
@wraps(f)
async def decorated_function(request, *args, **kwargs):
is_authenticated = check_token(request)
if is_authenticated:
response = await f(request, *args, **kwargs)
return response
else:
return text("token无效", 401)
return decorated_function
return decorator(wrapped)
main:
import jwt
from sanic import Sanic, text
from auth import login_required
app = Sanic("AuthApp")
app.config.SECRET = "KEEP_IT_SECRET_KEEP_IT_SAFE"
@app.post("/login")
async def login(request):
token = jwt.encode(request.json, request.app.config.SECRET)
return text(token)
@app.get("/secret")
@login_required
async def secret(request):
return text("已登录,可继续操作")
if __name__ == '__main__':
import uvicorn
uvicorn.run('main:app', host='0.0.0.0', port=8000, debug=True)