# Flask PASETO Extended

[](https://badge.fury.io/py/flask-paseto-extended)

[](https://flask-paseto-extended.readthedocs.io/en/latest/?badge=latest)

[](https://codecov.io/gh/dajiaji/flask-paseto-extended)
Flask-PASETO-Extended provides following four classes to use [PASETO (Platform-Agnostic Security Tokens)](https://paseto.io/) for Flask applications:
- **PasetoIssuer**
- This class can be used for issuing `public` (signed) PASETO. It is suitable for using PASETO as API tokens.
- **PasetoVerifier**
- This class can be used for verifying `public` (signed) PASETO. It is suitable for using PASETO as API tokens.
- **PasetoCookieSessionInterface**
- Flask (`Flask.sessions`) stores session information as a Cookie value. By using this class, you can serialize the session information as a `local` (encrypted and then MACed) PASETO.
- **PasetoLoginManager**
- By using this class together with [Flask-Login](https://github.com/maxcountryman/flask-login), you can use a `local` PASETO for remember-me tokens which is also encoded into a Cookie value.
For encoding/decoding PASETO, we have adopted [PySETO](https://github.com/dajiaji/pyseto),
which is a PASETO/PASERK implementation supporting all of PASETO versions (
[v4](https://github.com/paseto-standard/paseto-spec/blob/master/docs/01-Protocol-Versions/Version4.md),
[v3](https://github.com/paseto-standard/paseto-spec/blob/master/docs/01-Protocol-Versions/Version3.md),
[v2](https://github.com/paseto-standard/paseto-spec/blob/master/docs/01-Protocol-Versions/Version2.md) and
[v1](https://github.com/paseto-standard/paseto-spec/blob/master/docs/01-Protocol-Versions/Version1.md)) and purposes (`local` and `public`).
## Index
- [Installation](#installation)
- [Basic Usage](#basic-usage)
- [PasetoIssuer/PasetoVerifier](#pasetoissuerverifier)
- [PasetoCookieSessionInterface](#pasetocookiesessioninterface)
- [PasetoLoginManager](#pasetologinmanager)
- [API Reference](#api-reference)
- [Tests](#tests)
- [Contributing](#contributing)
## Installation
You can install Flask-PASETO-Extended with pip:
```sh
$ pip install flask-paseto-extended
```
## Basic Usage
Flask-PASETO-Extended provides three classes for each purpose.
### PasetoIssuer/Verifier
`PasetoIssuer` and `PasetoVerifier` can be used for issuing and verifying `public` (signed) PASETO tokens.
By using `PasetoIssuer`, you can easily implement the endpoint issuing PASETO tokens as follows:
```py
import flask
from flask_paseto_extended import PasetoIssuer
# Mock user database.
users = {"foo@bar.example": {"password": "mysecret"}}
app = flask.Flask(__name__)
app.config["PASETO_ISS"] = "https://issuer.example"
app.config["PASETO_PRIVATE_KEYS"] = [
{
"version": 4,
"key": "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEILTL+0PfTOIQcn2VPkpxMwf6Gbt9n4UEFDjZ4RuUKjd0\n-----END PRIVATE KEY-----",
},
# PASERK can also be used (RECOMMENDED).
# {
# "paserk": "k4.secret.tMv7Q99M4hByfZU-SnEzB_oZu32fhQQUONnhG5QqN3Qeudu7vAR8A_1wYE4AcfCYfhayi3VyJcEfAEFdDiCxog",
# },
]
issuer = PasetoIssuer(app)
@app.route("/login", methods=["POST"])
def login():
email = flask.request.form["email"]
if flask.request.form["password"] != users[email]["password"]:
return "Bad login"
token = issuer.issue(payload={"user": {"email": email}})
resp = flask.redirect(flask.url_for("protected_me"))
resp.set_cookie(
"paseto", token, httponly=True
) # Note: MUST add secure=True in production
return resp
```
On the other hand, by using `PasetoVerifier`, you can easily implement the endpoint verifying PASETO tokens. You can enable PASETO token verification in your APIs by simply adding `@paseto_required` decorator to the API definitions. In the APIs, you can refer to the veified PASETO token with `current_paseto`.
```py
import flask
from flask import jsonify, make_response
from flask_paseto_extended import PasetoVerifier, current_paseto, paseto_required
# Mock user database.
users = {"foo@bar.example": {"password": "mysecret"}}
app = flask.Flask(__name__)
# Configurations for PasetoVerifier.
app.config["PASETO_PUBLIC_KEYS"] = [
{
"iss": "https://issuer.exmaple",
"version": 4,
"key": "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAHrnbu7wEfAP9cGBOAHHwmH4Wsot1ciXBHwBBXQ4gsaI=\n-----END PUBLIC KEY-----",
},
# PASERK can also be used (RECOMMENDED).
# {
# "iss": "https://issuer.exmaple",
# "paserk": "k4.public.Hrnbu7wEfAP9cGBOAHHwmH4Wsot1ciXBHwBBXQ4gsaI",
# },
]
verifier = PasetoVerifier(app)
@verifier.token_loader
def token_loader(req: flask.Request):
# You must implement a callback func to extract a PASETO token from each request.
return req.cookies.get("paseto", None)
@verifier.verification_error_handler
def verification_error_handler():
# You must also implement a callback func to handle token verification errors..
resp = make_response("Unauthorized")
resp.delete_cookie("paseto", httponly=True)
return resp
@app.route("/protected/me")
@paseto_required()
def protected_me():
return jsonify(current_paseto.payload["user"])
```
See [examples/issuer_and_verifier.py](https://github.com/dajiaji/flask-paseto-extended/blob/main/examples/issuer_and_verifier.py) for a sample code that actually works.
### PasetoCookieSessionInterface
Flask (`Flask.sessions`) stores session information as a Cookie value. By using this class, you can serialize the session information as an encrypted (and then MACed) PASETO.
This class can be used as follows:
```py
import flask
from flask_paseto_extended import PasetoCookieSessionInterface
app = flask.Flask(__name__)
app.secret_key = "super secret string"
# Use PASETO("v4" by default) for cookie sessions.
app.session_interface = PasetoCookieSessionInterface()
```
See [examples/cookie_session.py](https://github.com/dajiaji/flask-paseto-extended/blob/main/examples/cookie_session.py) for a sample code that actually works.
### PasetoLoginManager
By using this class together with [Flask-Login](https://github.com/maxcountryman/flask-login), you can use PASETO for remember-me tokens which is also encoded into a Cookie value.
This class can be used as follows:
```py
import flask
import flask_login
# Import PasetoLoginManager instead of flask_login.LoginManager.
from flask_paseto_extended import PasetoLoginManager
app = flask.Flask(__name__)
app.secret_key = "super secret string"
login_manager = PasetoLoginManager(app)
```
See [examples/login_manager.py](https://github.com/dajiaji/flask-paseto-extended/blob/main/examples/login_manager.py) for a sample code that actually works.
## API Reference
See [Documentation](https://flask-paseto-extended.readthedocs.io/en/stable/api.html).
## Tests
You can run tests from the project root after cloning with:
```sh
$ tox
```
## Contributing
We welcome all kind of contributions, filing issues, suggesting new features or sending PRs.
Raw data
{
"_id": null,
"home_page": "https://github.com/dajiaji/flask-paseto-extended",
"name": "flask-paseto-extended",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.9",
"maintainer_email": null,
"keywords": null,
"author": "Ajitomi Daisuke",
"author_email": "dajiaji@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/20/77/42527fbcac6d410348aaf2217a8d04e442ca7ad3e03828df9add717af95a/flask_paseto_extended-0.6.0.tar.gz",
"platform": null,
"description": "# Flask PASETO Extended\n\n\n\n[](https://badge.fury.io/py/flask-paseto-extended)\n\n[](https://flask-paseto-extended.readthedocs.io/en/latest/?badge=latest)\n\n[](https://codecov.io/gh/dajiaji/flask-paseto-extended)\n\nFlask-PASETO-Extended provides following four classes to use [PASETO (Platform-Agnostic Security Tokens)](https://paseto.io/) for Flask applications:\n\n- **PasetoIssuer**\n - This class can be used for issuing `public` (signed) PASETO. It is suitable for using PASETO as API tokens.\n- **PasetoVerifier**\n - This class can be used for verifying `public` (signed) PASETO. It is suitable for using PASETO as API tokens.\n- **PasetoCookieSessionInterface**\n - Flask (`Flask.sessions`) stores session information as a Cookie value. By using this class, you can serialize the session information as a `local` (encrypted and then MACed) PASETO.\n- **PasetoLoginManager**\n - By using this class together with [Flask-Login](https://github.com/maxcountryman/flask-login), you can use a `local` PASETO for remember-me tokens which is also encoded into a Cookie value.\n\nFor encoding/decoding PASETO, we have adopted [PySETO](https://github.com/dajiaji/pyseto),\nwhich is a PASETO/PASERK implementation supporting all of PASETO versions (\n[v4](https://github.com/paseto-standard/paseto-spec/blob/master/docs/01-Protocol-Versions/Version4.md),\n[v3](https://github.com/paseto-standard/paseto-spec/blob/master/docs/01-Protocol-Versions/Version3.md),\n[v2](https://github.com/paseto-standard/paseto-spec/blob/master/docs/01-Protocol-Versions/Version2.md) and\n[v1](https://github.com/paseto-standard/paseto-spec/blob/master/docs/01-Protocol-Versions/Version1.md)) and purposes (`local` and `public`).\n\n## Index\n- [Installation](#installation)\n- [Basic Usage](#basic-usage)\n - [PasetoIssuer/PasetoVerifier](#pasetoissuerverifier)\n - [PasetoCookieSessionInterface](#pasetocookiesessioninterface)\n - [PasetoLoginManager](#pasetologinmanager)\n- [API Reference](#api-reference)\n- [Tests](#tests)\n- [Contributing](#contributing)\n\n## Installation\n\nYou can install Flask-PASETO-Extended with pip:\n\n```sh\n$ pip install flask-paseto-extended\n```\n\n## Basic Usage\n\nFlask-PASETO-Extended provides three classes for each purpose.\n\n### PasetoIssuer/Verifier\n\n`PasetoIssuer` and `PasetoVerifier` can be used for issuing and verifying `public` (signed) PASETO tokens.\n\nBy using `PasetoIssuer`, you can easily implement the endpoint issuing PASETO tokens as follows:\n\n```py\nimport flask\n\nfrom flask_paseto_extended import PasetoIssuer\n\n# Mock user database.\nusers = {\"foo@bar.example\": {\"password\": \"mysecret\"}}\n\n\napp = flask.Flask(__name__)\n\napp.config[\"PASETO_ISS\"] = \"https://issuer.example\"\napp.config[\"PASETO_PRIVATE_KEYS\"] = [\n {\n \"version\": 4,\n \"key\": \"-----BEGIN PRIVATE KEY-----\\nMC4CAQAwBQYDK2VwBCIEILTL+0PfTOIQcn2VPkpxMwf6Gbt9n4UEFDjZ4RuUKjd0\\n-----END PRIVATE KEY-----\",\n },\n # PASERK can also be used (RECOMMENDED).\n # {\n # \"paserk\": \"k4.secret.tMv7Q99M4hByfZU-SnEzB_oZu32fhQQUONnhG5QqN3Qeudu7vAR8A_1wYE4AcfCYfhayi3VyJcEfAEFdDiCxog\",\n # },\n]\nissuer = PasetoIssuer(app)\n\n\n@app.route(\"/login\", methods=[\"POST\"])\ndef login():\n email = flask.request.form[\"email\"]\n if flask.request.form[\"password\"] != users[email][\"password\"]:\n return \"Bad login\"\n\n token = issuer.issue(payload={\"user\": {\"email\": email}})\n resp = flask.redirect(flask.url_for(\"protected_me\"))\n resp.set_cookie(\n \"paseto\", token, httponly=True\n ) # Note: MUST add secure=True in production\n return resp\n```\n\nOn the other hand, by using `PasetoVerifier`, you can easily implement the endpoint verifying PASETO tokens. You can enable PASETO token verification in your APIs by simply adding `@paseto_required` decorator to the API definitions. In the APIs, you can refer to the veified PASETO token with `current_paseto`.\n\n```py\nimport flask\nfrom flask import jsonify, make_response\n\nfrom flask_paseto_extended import PasetoVerifier, current_paseto, paseto_required\n\n# Mock user database.\nusers = {\"foo@bar.example\": {\"password\": \"mysecret\"}}\n\napp = flask.Flask(__name__)\n\n# Configurations for PasetoVerifier.\napp.config[\"PASETO_PUBLIC_KEYS\"] = [\n {\n \"iss\": \"https://issuer.exmaple\",\n \"version\": 4,\n \"key\": \"-----BEGIN PUBLIC KEY-----\\nMCowBQYDK2VwAyEAHrnbu7wEfAP9cGBOAHHwmH4Wsot1ciXBHwBBXQ4gsaI=\\n-----END PUBLIC KEY-----\",\n },\n # PASERK can also be used (RECOMMENDED).\n # {\n # \"iss\": \"https://issuer.exmaple\",\n # \"paserk\": \"k4.public.Hrnbu7wEfAP9cGBOAHHwmH4Wsot1ciXBHwBBXQ4gsaI\",\n # },\n]\nverifier = PasetoVerifier(app)\n\n\n@verifier.token_loader\ndef token_loader(req: flask.Request):\n # You must implement a callback func to extract a PASETO token from each request.\n return req.cookies.get(\"paseto\", None)\n\n\n@verifier.verification_error_handler\ndef verification_error_handler():\n # You must also implement a callback func to handle token verification errors..\n resp = make_response(\"Unauthorized\")\n resp.delete_cookie(\"paseto\", httponly=True)\n return resp\n\n\n@app.route(\"/protected/me\")\n@paseto_required()\ndef protected_me():\n return jsonify(current_paseto.payload[\"user\"])\n```\n\nSee [examples/issuer_and_verifier.py](https://github.com/dajiaji/flask-paseto-extended/blob/main/examples/issuer_and_verifier.py) for a sample code that actually works.\n\n\n### PasetoCookieSessionInterface\n\nFlask (`Flask.sessions`) stores session information as a Cookie value. By using this class, you can serialize the session information as an encrypted (and then MACed) PASETO.\n\nThis class can be used as follows:\n\n```py\nimport flask\nfrom flask_paseto_extended import PasetoCookieSessionInterface\n\napp = flask.Flask(__name__)\napp.secret_key = \"super secret string\"\n\n# Use PASETO(\"v4\" by default) for cookie sessions.\napp.session_interface = PasetoCookieSessionInterface()\n```\n\nSee [examples/cookie_session.py](https://github.com/dajiaji/flask-paseto-extended/blob/main/examples/cookie_session.py) for a sample code that actually works.\n\n### PasetoLoginManager\n\nBy using this class together with [Flask-Login](https://github.com/maxcountryman/flask-login), you can use PASETO for remember-me tokens which is also encoded into a Cookie value.\n\nThis class can be used as follows:\n\n```py\nimport flask\nimport flask_login\n\n# Import PasetoLoginManager instead of flask_login.LoginManager.\nfrom flask_paseto_extended import PasetoLoginManager\n\napp = flask.Flask(__name__)\napp.secret_key = \"super secret string\"\n\nlogin_manager = PasetoLoginManager(app)\n```\n\nSee [examples/login_manager.py](https://github.com/dajiaji/flask-paseto-extended/blob/main/examples/login_manager.py) for a sample code that actually works.\n\n## API Reference\n\nSee [Documentation](https://flask-paseto-extended.readthedocs.io/en/stable/api.html).\n\n\n## Tests\n\nYou can run tests from the project root after cloning with:\n\n```sh\n$ tox\n```\n\n## Contributing\n\nWe welcome all kind of contributions, filing issues, suggesting new features or sending PRs.\n",
"bugtrack_url": null,
"license": null,
"summary": "PASETO (Platform-Agnostic Security Tokens) for Flask applications.",
"version": "0.6.0",
"project_urls": {
"Homepage": "https://github.com/dajiaji/flask-paseto-extended",
"Repository": "https://github.com/dajiaji/flask-paseto-extended"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "f16890b92f140ceb3c14163ff443f8094494e01c164097399794376adb4df791",
"md5": "ef5f54b96a83e3943c13127182a85dc0",
"sha256": "6d0bff3dd2847b2529dc7becbb9065e67fe02c8243c1f615755f1aa6ad019e7c"
},
"downloads": -1,
"filename": "flask_paseto_extended-0.6.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "ef5f54b96a83e3943c13127182a85dc0",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.9",
"size": 49436,
"upload_time": "2024-11-16T01:41:04",
"upload_time_iso_8601": "2024-11-16T01:41:04.527438Z",
"url": "https://files.pythonhosted.org/packages/f1/68/90b92f140ceb3c14163ff443f8094494e01c164097399794376adb4df791/flask_paseto_extended-0.6.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "207742527fbcac6d410348aaf2217a8d04e442ca7ad3e03828df9add717af95a",
"md5": "12fe6e15af6664f06dec7ac486d04abe",
"sha256": "7eeeb193a34b2187e633606093e851fd94179096e679397c932e334c4e5e8ff8"
},
"downloads": -1,
"filename": "flask_paseto_extended-0.6.0.tar.gz",
"has_sig": false,
"md5_digest": "12fe6e15af6664f06dec7ac486d04abe",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.9",
"size": 58298,
"upload_time": "2024-11-16T01:41:06",
"upload_time_iso_8601": "2024-11-16T01:41:06.748574Z",
"url": "https://files.pythonhosted.org/packages/20/77/42527fbcac6d410348aaf2217a8d04e442ca7ad3e03828df9add717af95a/flask_paseto_extended-0.6.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-11-16 01:41:06",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "dajiaji",
"github_project": "flask-paseto-extended",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"tox": true,
"lcname": "flask-paseto-extended"
}