Skip to content

Instantly share code, notes, and snippets.

@rscarrera27
Last active November 23, 2019 09:12
Show Gist options
  • Save rscarrera27/3f90cde7a9370b3c7e7555476a38ef6c to your computer and use it in GitHub Desktop.
Save rscarrera27/3f90cde7a9370b3c7e7555476a38ef6c to your computer and use it in GitHub Desktop.
from sanic import Sanic
from sanic.response import json
from sanic.request import Request
from sanic_jwt_extended import JWT
import uuid
app = Sanic(__name__)
def my_expired_token_callback():
pass
# Setup the Sanic-JWT-Extended extension
with JWT.init(app) as jwt:
jwt.config.use_acl = False
jwt.config.secret_key = "super-secret"
jwt.callback.expried_token = my_expired_token_callback
# after close this context, you can *not* modify config and callback.
@app.route("/login", methods=["POST"])
async def login(request: Request):
username = request.json.get("username", None)
password = request.json.get("password", None)
access_token = await JWT.create_access_token(sub=username)
refresh_token = await JWT.create_refresh_token(sub=uuid.uuid4())
return json(
dict(access_token=access_token, refresh_token=refresh_token), status=200
)
# Protect a view with jwt_required, which requires a valid access token
# in the request to access.
@app.route("/protected", methods=["GET"])
@jwt_required
async def protected(request: Request):
# Access the identity of the current user with get_jwt_identity
raw_jwt = requet.token.raw_jwt
current_user = request.token.sub
return json(dict(logined_as=current_user))
if __name__ == "__main__":
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment