flask-pyjwt


Nameflask-pyjwt JSON
Version 1.0.0 PyPI version JSON
download
home_pagehttps://flask-pyjwt.readthedocs.io/
SummaryFlask extension for creating, verifying, and requiring the presence of JWTs
upload_time2023-01-24 23:11:50
maintainer
docs_urlNone
authorCarson Mullins
requires_python>=3.8,<4.0
licenseMIT
keywords flask authentication jwt security
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ###########
Flask_PyJWT
###########

Flast_PyJWT is a flask extension for adding authentication and authorization via
JWT tokens. Routes can be decorated to require JWT auth or refresh tokens, and can
require the presence of additional claims and their values.

************
Installation
************

Flask_PyJWT can be installed with ``pip``:

.. code-block:: console

    pip install Flask_PyJWT

A python version of 3.8 or higher is officially supported. Other versions of Python 3.x
may work, but have not been tested.

Currently, only Flask 1.1.x is officially supported. Flask 2.x *may* work, but has not
been tested.

*************
Documentation
*************

Documentation is hosted by `Read the Docs <https://readthedocs.org/>`_.

You can find documentation for Flask_PyJWT at `<https://flask-pyjwt.readthedocs.io/>`_

*************
Configuration
*************

Flask_PyJWT's configuration variables are read from the Flask app's config and start
with the prefix "JWT\_".

Required Values
===============

JWT_ISSUER
----------

(``str``): The issuer of JWTs. Usually your website/API's name.

JWT_AUTHTYPE
------------

(``str``): The type of auth to use for your JWTs (HMACSHA256, HMACSHA512, RSA256, RSA512).

Accepted Values:

* HS256
* HS512
* RS256
* RS512

JWT_SECRET
----------

(``str`` | ``bytes``): The secret key or RSA private key to sign JWTs with.

If the ``JWT_AUTHTYPE`` is HS256 or HS512, a ``str`` is required.
if the ``JWT_AUTHTYPE`` is RS256 or RS512, a ``bytes`` encoded RSA private key is required.

Optional Values
===============

JWT_AUTHMAXAGE
--------------

(``int``): The maximum time, in seconds, that an auth JWT is considered valid.

JWT_REFRESHMAXAGE
-----------------
(``int``): The maximum time, in seconds, that a refresh JWT is considered valid.

JWT_PUBLICKEY
-------------

(``str`` | ``bytes``): The RSA public key used to verify JWTs with, if the ``JWT_AUTHTYPE``
is set to RS256 or RS512.


*************
Example Usage
*************

.. code-block:: python

    from Flask import flask, request
    from Flask_PyJWT import auth_manager, current_token, require_token

    app = Flask(__name__)
    app.config["JWT_ISSUER"] = "Flask_PyJWT" # Issuer of tokens
    app.config["JWT_AUTHTYPE"] = "HS256" # HS256, HS512, RS256, or RS512
    app.config["JWT_SECRET"] = "SECRETKEY" # string for HS256/HS512, bytes (RSA Private Key) for RS256/RS512
    app.config["JWT_AUTHMAXAGE"] = 3600
    app.config["JWT_REFRESHMAXAGE"] = 604800

    auth_manager = AuthManager(app)

    # Create auth and refresh tokens with the auth_manager object
    @app.route("/login", METHODS=["POST"])
    def post_token():
        username = request.form["username"]
        password = request.form["password"]
        # Some user authentication via username/password
        if not valid_login(username, password):
            return {"error": "Invalid login credentials"}, 401
        # Retrieve some authorizations the user has, such as {"admin": True}
        authorizations = get_user_authorizations(username)
        # Create the auth and refresh tokens
        auth_token = auth_manager.auth_token(username, authorizations)
        refresh_token = auth_manager.refresh_token(username)
        return {
            "auth_token": auth_token.signed, 
            "refresh_token": refresh_token.signed
        }, 200
    
    # Protect routes by requiring auth tokens
    @app.route("/protected_route")
    @require_token()
    def protected_route():
        return {"message": "You've reached the protected route!"}, 200
    
    # Provision new auth tokens by requiring refresh tokens
    @app.route("/refresh", method=["POST"])
    @require_token("refresh")
    def refresh_token_route():
        username = current_token.sub
        # Retrieve some authorizations the user has, such as {"admin": True}
        authorizations = get_user_authorizations(username)
        new_auth_token = auth_manager.auth_token(username, authorizations)
        return {
            "auth_token": new_auth_token.signed
        }, 200
    
    # Require specific claims in auth or refresh tokens
    # to match a route's rule variables
    @app.route("/user_specific_route/<string:username>")
    @require_token(sub="username")
    def user_specific_route(username):
        return {"message": f"Hello, {username}!"}, 200
    
    # Require arbitrary claims in auth or refresh tokens
    @app.route("/custom_claim_route")
    @require_token(custom_claim="Arbitrary Required Value")
    def custom_claim_route():
        return {"message": "You've reached the custom claim route!"}, 200
    
    # Require authorizations to be present in an auth token's scope
    @app.route("/admin_dashboard")
    @require_token(scope={"admin": True})
    def admin_dashboard():
        return {"message": f"Hello admin!"}
    
    # Access the current token's information using current_token
    @app.route("/token/info")
    @require_token()
    def extract_token_info():
        return {
            "token_type": current_token.token_type,
            "subject": current_token.sub,
            "scope": current_token.scope,
            "claims": current_token.claims,
            "is_signed": current_token.is_signed()
            "signed_token": current_token.signed,
        }

    # Require authorization to be present in an auth token's scope or claims, but
    # with the option to override those values with other claims
    @app.route("/overridable_route/<string:username>")
    @require_token(sub="username", override={"admin": True})
    def overridable_route():
        is_admin = current_token.claims.get("admin")
        return {"message": f"Hello, {'admin' if is_admin else username}!"}, 200

            

Raw data

            {
    "_id": null,
    "home_page": "https://flask-pyjwt.readthedocs.io/",
    "name": "flask-pyjwt",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<4.0",
    "maintainer_email": "",
    "keywords": "flask,authentication,jwt,security",
    "author": "Carson Mullins",
    "author_email": "septem151@protonmail.com",
    "download_url": "https://files.pythonhosted.org/packages/36/00/1636bb3268f7547387d020959a61cfc3223de277369784ebcccbc24dc50b/flask_pyjwt-1.0.0.tar.gz",
    "platform": null,
    "description": "###########\nFlask_PyJWT\n###########\n\nFlast_PyJWT is a flask extension for adding authentication and authorization via\nJWT tokens. Routes can be decorated to require JWT auth or refresh tokens, and can\nrequire the presence of additional claims and their values.\n\n************\nInstallation\n************\n\nFlask_PyJWT can be installed with ``pip``:\n\n.. code-block:: console\n\n    pip install Flask_PyJWT\n\nA python version of 3.8 or higher is officially supported. Other versions of Python 3.x\nmay work, but have not been tested.\n\nCurrently, only Flask 1.1.x is officially supported. Flask 2.x *may* work, but has not\nbeen tested.\n\n*************\nDocumentation\n*************\n\nDocumentation is hosted by `Read the Docs <https://readthedocs.org/>`_.\n\nYou can find documentation for Flask_PyJWT at `<https://flask-pyjwt.readthedocs.io/>`_\n\n*************\nConfiguration\n*************\n\nFlask_PyJWT's configuration variables are read from the Flask app's config and start\nwith the prefix \"JWT\\_\".\n\nRequired Values\n===============\n\nJWT_ISSUER\n----------\n\n(``str``): The issuer of JWTs. Usually your website/API's name.\n\nJWT_AUTHTYPE\n------------\n\n(``str``): The type of auth to use for your JWTs (HMACSHA256, HMACSHA512, RSA256, RSA512).\n\nAccepted Values:\n\n* HS256\n* HS512\n* RS256\n* RS512\n\nJWT_SECRET\n----------\n\n(``str`` | ``bytes``): The secret key or RSA private key to sign JWTs with.\n\nIf the ``JWT_AUTHTYPE`` is HS256 or HS512, a ``str`` is required.\nif the ``JWT_AUTHTYPE`` is RS256 or RS512, a ``bytes`` encoded RSA private key is required.\n\nOptional Values\n===============\n\nJWT_AUTHMAXAGE\n--------------\n\n(``int``): The maximum time, in seconds, that an auth JWT is considered valid.\n\nJWT_REFRESHMAXAGE\n-----------------\n(``int``): The maximum time, in seconds, that a refresh JWT is considered valid.\n\nJWT_PUBLICKEY\n-------------\n\n(``str`` | ``bytes``): The RSA public key used to verify JWTs with, if the ``JWT_AUTHTYPE``\nis set to RS256 or RS512.\n\n\n*************\nExample Usage\n*************\n\n.. code-block:: python\n\n    from Flask import flask, request\n    from Flask_PyJWT import auth_manager, current_token, require_token\n\n    app = Flask(__name__)\n    app.config[\"JWT_ISSUER\"] = \"Flask_PyJWT\" # Issuer of tokens\n    app.config[\"JWT_AUTHTYPE\"] = \"HS256\" # HS256, HS512, RS256, or RS512\n    app.config[\"JWT_SECRET\"] = \"SECRETKEY\" # string for HS256/HS512, bytes (RSA Private Key) for RS256/RS512\n    app.config[\"JWT_AUTHMAXAGE\"] = 3600\n    app.config[\"JWT_REFRESHMAXAGE\"] = 604800\n\n    auth_manager = AuthManager(app)\n\n    # Create auth and refresh tokens with the auth_manager object\n    @app.route(\"/login\", METHODS=[\"POST\"])\n    def post_token():\n        username = request.form[\"username\"]\n        password = request.form[\"password\"]\n        # Some user authentication via username/password\n        if not valid_login(username, password):\n            return {\"error\": \"Invalid login credentials\"}, 401\n        # Retrieve some authorizations the user has, such as {\"admin\": True}\n        authorizations = get_user_authorizations(username)\n        # Create the auth and refresh tokens\n        auth_token = auth_manager.auth_token(username, authorizations)\n        refresh_token = auth_manager.refresh_token(username)\n        return {\n            \"auth_token\": auth_token.signed, \n            \"refresh_token\": refresh_token.signed\n        }, 200\n    \n    # Protect routes by requiring auth tokens\n    @app.route(\"/protected_route\")\n    @require_token()\n    def protected_route():\n        return {\"message\": \"You've reached the protected route!\"}, 200\n    \n    # Provision new auth tokens by requiring refresh tokens\n    @app.route(\"/refresh\", method=[\"POST\"])\n    @require_token(\"refresh\")\n    def refresh_token_route():\n        username = current_token.sub\n        # Retrieve some authorizations the user has, such as {\"admin\": True}\n        authorizations = get_user_authorizations(username)\n        new_auth_token = auth_manager.auth_token(username, authorizations)\n        return {\n            \"auth_token\": new_auth_token.signed\n        }, 200\n    \n    # Require specific claims in auth or refresh tokens\n    # to match a route's rule variables\n    @app.route(\"/user_specific_route/<string:username>\")\n    @require_token(sub=\"username\")\n    def user_specific_route(username):\n        return {\"message\": f\"Hello, {username}!\"}, 200\n    \n    # Require arbitrary claims in auth or refresh tokens\n    @app.route(\"/custom_claim_route\")\n    @require_token(custom_claim=\"Arbitrary Required Value\")\n    def custom_claim_route():\n        return {\"message\": \"You've reached the custom claim route!\"}, 200\n    \n    # Require authorizations to be present in an auth token's scope\n    @app.route(\"/admin_dashboard\")\n    @require_token(scope={\"admin\": True})\n    def admin_dashboard():\n        return {\"message\": f\"Hello admin!\"}\n    \n    # Access the current token's information using current_token\n    @app.route(\"/token/info\")\n    @require_token()\n    def extract_token_info():\n        return {\n            \"token_type\": current_token.token_type,\n            \"subject\": current_token.sub,\n            \"scope\": current_token.scope,\n            \"claims\": current_token.claims,\n            \"is_signed\": current_token.is_signed()\n            \"signed_token\": current_token.signed,\n        }\n\n    # Require authorization to be present in an auth token's scope or claims, but\n    # with the option to override those values with other claims\n    @app.route(\"/overridable_route/<string:username>\")\n    @require_token(sub=\"username\", override={\"admin\": True})\n    def overridable_route():\n        is_admin = current_token.claims.get(\"admin\")\n        return {\"message\": f\"Hello, {'admin' if is_admin else username}!\"}, 200\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Flask extension for creating, verifying, and requiring the presence of JWTs",
    "version": "1.0.0",
    "split_keywords": [
        "flask",
        "authentication",
        "jwt",
        "security"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4ffbbd83c93f5d7d43aa6cb1148ca6bae4406b8662d324964d281f80feff4a09",
                "md5": "9f7364bc6083d0aab91756171c4e953a",
                "sha256": "42d5f7651e65b34d4c6ed9fdcb042c962b2a64b4e50b732c8dce266bceec435b"
            },
            "downloads": -1,
            "filename": "flask_pyjwt-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "9f7364bc6083d0aab91756171c4e953a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<4.0",
            "size": 14968,
            "upload_time": "2023-01-24T23:11:48",
            "upload_time_iso_8601": "2023-01-24T23:11:48.767105Z",
            "url": "https://files.pythonhosted.org/packages/4f/fb/bd83c93f5d7d43aa6cb1148ca6bae4406b8662d324964d281f80feff4a09/flask_pyjwt-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "36001636bb3268f7547387d020959a61cfc3223de277369784ebcccbc24dc50b",
                "md5": "28a70cf104d1cbcdcf2cf0dcfce8741d",
                "sha256": "0a7d8e191eaaadf8146757b3798803927acf0732071c341ee0a83ed6ca12458b"
            },
            "downloads": -1,
            "filename": "flask_pyjwt-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "28a70cf104d1cbcdcf2cf0dcfce8741d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<4.0",
            "size": 14686,
            "upload_time": "2023-01-24T23:11:50",
            "upload_time_iso_8601": "2023-01-24T23:11:50.592035Z",
            "url": "https://files.pythonhosted.org/packages/36/00/1636bb3268f7547387d020959a61cfc3223de277369784ebcccbc24dc50b/flask_pyjwt-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-01-24 23:11:50",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "lcname": "flask-pyjwt"
}
        
Elapsed time: 0.27522s