Skip to content

Sanic with jwt

项目结构

plaintext
project_root/

├── demo/
│   ├── __init__.py
│   ├── server.py
│   └── auth.py

└── pyproject.toml

依赖环境

toml
[tool.poetry.dependencies]
python = "^3.9"
sanic = "^23.6.0"
pyjwt = "^2.8.0"

代码

python
from sanic import Sanic, text, Blueprint
import jwt

from handlers.auth import protected

app = Sanic("AuthApp")
app.config.SECRET = "KEEP_IT_SECRET_KEEP_IT_SAFE"

api = Blueprint('api', url_prefix='/api')
app.blueprint(api)

@api.post("/login")
async def do_login(request):
    token = jwt.encode({}, app.config.SECRET)
    return text(token)

@api.get("/secret")
@protected
async def secret(request):
    return text("To go fast, you must be fast.")

if __name__ == '__main__':
    app.run(host="127.0.0.1", port=80, access_log=True, auto_reload=True)
python
from functools import wraps
import jwt
from sanic import text

def check_token(request):
    if not request.token:
        return False

    try:
        jwt.decode(request.token, request.app.config.SECRET, algorithms=["HS256"])
    except jwt.exceptions.InvalidTokenError:
        return False
    else:
        return True

def protected(wrapped):
    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("You are unauthorized.", 401)

        return decorated_function

    return decorator(wrapped)

For additional details, refer to the Sanic Authentication Guide. This guide provides insights into enhancing authentication mechanisms in Sanic applications.

Released under the MIT License.