安装pyjwt:pip install pyjwt

Sanic十五:Sanic + pyjwt 实现token验证_ico

 

pyjwt的使用,主要是一个加密,一个解密

Sanic十五:Sanic + pyjwt 实现token验证_json_02

Sanic十五:Sanic + pyjwt 实现token验证_ico_03

 

token校验代码

Sanic十五:Sanic + pyjwt 实现token验证_ico_04

Sanic十五:Sanic + pyjwt 实现token验证_ico_05

 

在视图中使用

Sanic十五:Sanic + pyjwt 实现token验证_函数参数_06

 

1、登录,获取token

Sanic十五:Sanic + pyjwt 实现token验证_函数参数_07

 

2、用token请求需校验token的接口

Sanic十五:Sanic + pyjwt 实现token验证_函数参数_08

 

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)

 

讨论群:249728408