{"library":"sanic-jwt","title":"Sanic JWT","description":"Sanic-JWT provides a JWT (JSON Web Token) authentication flow for the Sanic web framework. It simplifies the process of user authentication, token generation, and securing endpoints. The library is currently at version 1.8.0, with releases focused on compatibility with newer Sanic and PyJWT versions, and feature enhancements.","language":"python","status":"active","last_verified":"Thu Apr 16","install":{"commands":["pip install sanic-jwt"],"cli":null},"imports":["from sanic_jwt import SanicJWT","from sanic_jwt import protected","from sanic_jwt import Configuration"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"from sanic import Sanic, response\nfrom sanic_jwt import SanicJWT, protected\nimport os\n\napp = Sanic(\"my_jwt_app\")\n\n# Set a secret key for JWT signing. Crucial for security.\napp.config.SANIC_JWT_SECRET = os.environ.get(\"SANIC_JWT_SECRET\", \"your-super-secret-key-that-no-one-knows\")\n\n# Define an asynchronous authentication function.\n# This function handles both token verification (payload present) and user login (payload None).\nasync def authenticate(request, payload):\n    if payload: # Token verification for protected routes\n        # In a real app, you'd fetch user data from a DB based on payload (e.g., user_id)\n        user_id = payload.get(\"user_id\")\n        if user_id:\n            return {\"user_id\": user_id, \"username\": payload.get(\"username\", \"user\")} # Return user info for ctx\n        return False\n    else: # User login attempt for the /auth endpoint\n        # Expect username/password in request.json\n        username = request.json.get(\"username\")\n        password = request.json.get(\"password\")\n\n        if username == \"test\" and password == \"test\": # Dummy check\n            return {\"user_id\": 1, \"username\": \"testuser\"} # Return user info to be included in JWT payload\n        return False # Authentication failed\n\n# Initialize Sanic-JWT with the app and your custom authentication function.\nSanicJWT.setup(app, authenticate=authenticate)\n\n@app.route(\"/protected\")\n@protected()\nasync def protected_route(request):\n    # Access user data via request.ctx.user after successful authentication\n    username = request.ctx.user.get('username', 'authenticated user')\n    return response.json({\"message\": f\"Hello, {username}! This is a protected route.\"})\n\n@app.get(\"/public\")\nasync def public_route(request):\n    return response.json({\"message\": \"This is a public route, accessible without a token.\"})\n\nif __name__ == \"__main__\":\n    # To run:\n    # 1. Start the app: python your_script_name.py\n    # 2. Login (obtain token): curl -X POST -H \"Content-Type: application/json\" -d '{\"username\":\"test\",\"password\":\"test\"}' http://localhost:8000/auth\n    # 3. Access protected route with token: curl -H \"Authorization: Bearer <your_token_here>\" http://localhost:8000/protected\n    app.run(host=\"0.0.0.0\", port=8000, debug=True)\n","lang":"python","description":"This quickstart demonstrates how to set up `sanic-jwt` with a Sanic application. It includes a simple authentication function, a protected route using the `@protected()` decorator, and a public route. Users obtain a JWT by POSTing to the `/auth` endpoint with credentials, and then use this token in the `Authorization: Bearer` header for protected routes.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}