安装pyjwt:pip install pyjwt

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

 

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

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

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

 

token校验代码

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

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

 

在视图中使用

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

 

1、登录,获取token

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

 

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

Sanic十五:Sanic + pyjwt 实现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)

 

相关文章:

  • 2021-12-28
  • 2021-06-12
  • 2021-10-16
  • 2021-07-25
  • 2021-12-04
  • 2021-08-18
  • 2021-11-27
  • 2022-01-31
猜你喜欢
  • 2022-01-10
  • 2021-07-12
  • 2021-09-25
  • 2021-12-06
  • 2021-10-17
  • 2022-02-22
  • 2021-11-22
相关资源
相似解决方案