{"id":13698032,"url":"https://github.com/audiolion/apistar-jwt","last_synced_at":"2025-05-04T00:31:02.774Z","repository":{"id":57410927,"uuid":"105830634","full_name":"audiolion/apistar-jwt","owner":"audiolion","description":"A JSON Web Token Component for API Star","archived":true,"fork":false,"pushed_at":"2019-10-18T16:22:28.000Z","size":66,"stargazers_count":40,"open_issues_count":0,"forks_count":8,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-08T14:17:17.369Z","etag":null,"topics":["apistar","apistar-jwt","jwt","jwt-authentication","jwt-component"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/audiolion.png","metadata":{"files":{"readme":"README.md","changelog":"HISTORY.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-10-04T23:42:51.000Z","updated_at":"2025-02-25T13:27:28.000Z","dependencies_parsed_at":"2022-08-27T22:02:07.331Z","dependency_job_id":null,"html_url":"https://github.com/audiolion/apistar-jwt","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/audiolion%2Fapistar-jwt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/audiolion%2Fapistar-jwt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/audiolion%2Fapistar-jwt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/audiolion%2Fapistar-jwt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/audiolion","download_url":"https://codeload.github.com/audiolion/apistar-jwt/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252272944,"owners_count":21721831,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["apistar","apistar-jwt","jwt","jwt-authentication","jwt-component"],"created_at":"2024-08-02T19:00:24.809Z","updated_at":"2025-05-04T00:31:02.458Z","avatar_url":"https://github.com/audiolion.png","language":"Python","funding_links":[],"categories":["Packages"],"sub_categories":["Authentication"],"readme":"# apistar-jwt\n\n[![pypi](https://img.shields.io/pypi/v/apistar_jwt.svg)](https://pypi.org/project/apistar-jwt) [![travis](https://img.shields.io/travis/audiolion/apistar-jwt.svg)](https://travis-ci.org/audiolion/apistar_jwt) [![codecov](https://codecov.io/gh/audiolion/apistar-jwt/branch/master/graph/badge.svg)](https://codecov.io/gh/audiolion/apistar-jwt)\n\n## DEPRECATION NOTICE\n\nAPI Star gutted a lot of functionality to go a different path. As a result, this library will be obsolete. I don't intend to continue to maintain it.\n\nIf you liked the spirit of API Star, I would recommend checking out [Molten](https://moltenframework.com/) and [Molten JWT](https://github.com/androiddrew/molten-jwt).\n\n----------------------\nJSON Web Token Component for use with *API Star 0.4 \u003c= x \u003c 0.6.\n\n## Installation\n\n```\n$ pip install apistar-jwt\n```\n\nAlternatively, install through [pipenv](https://pipenv.readthedocs.io/en/latest/).\n\n```\n$ pipenv install apistar-jwt\n```\n\n## Usage\n\n\nRegister the `JWT` Component with your APIStar app.\n\n```python\nfrom apistar import App\nfrom apistar_jwt.token import JWT\n\nroutes = [\n  # ...\n]\n\ncomponents = [\n    JWT({\n        'JWT_SECRET': 'BZz4bHXYQD?g9YN2UksRn7*r3P(eo]P,Rt8NCWKs6VP34qmTL#8f\u0026ruD^TtG',\n    }),\n]\n\napp = App(routes=routes, components=components)\n```\n\nInject the `JWT` component in your login function and use it to encode the JWT.\n\n```python\nfrom apistar import exceptions, types, validators\nfrom apistar_jwt.token import JWT\n\nclass UserData(types.Type):\n    email = validators.String()\n    password = validators.String()\n\n\ndef login(data: UserData, jwt: JWT) -\u003e dict:\n    # do some check with your database here to see if the user is authenticated\n    user = db_login(data)\n    if not user:\n        raise exceptions.Forbidden('Incorrect username or password.')\n    payload = {\n        'id': user.id,\n        'username': user.email,\n        'random_data': '102310',\n    }\n    token = jwt.encode(payload)\n    if token is None:\n        # encoding failed, handle error\n        raise exceptions.BadRequest()\n    return {'token': token}\n```\n\nInject the `JWTUser` component in any resource where you want authentication with the provided JWT.\n\n```python\nfrom apistar_jwt.token import JWTUser\n\ndef welcome(user: JWTUser) -\u003e dict:\n    message = f'Welcome {user.username}#{user.id}, here is your random data: {user.token[\"random_data\"]}'\n    return {'message': message}\n```\n\n**Note**\n\nRequests made with JWT The token must be passed as an `Authorization` header using the `Bearer` scheme in requests made to a resource.\n\n```shell\n$ curl -i -H \"Accept: application/json\" -H \"Content-Type: application/json\" -H \"Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoxfQ.fCqeAJGHYwZ9y-hJ3CKUWPiENOM0xtGsMeUWmIq4o8Q\" http://localhost:8080/some-resource-requiring-jwt-auth\n```\n\n### Decorators\n\nWe provide two decorators for convenience to enforce authentication required or allow anonymous users for a route:\n\n```python\nfrom apistar_jwt.token import JWTUser\nfrom apistar_jwt.decorators import anonymous_allowed, authentication_required\n\n\n@authentication_required\ndef auth_required(request: http.Request, user: JWTUser):\n    return user.__dict__\n\n\n@anonymous_allowed\ndef anon_allowed(request: http.Request, user: JWTUser):\n    if user:\n        return user.__dict__\n    return None\n```\n\nThe `@authentication_required` decorator will enforce the user to be logged in for that route. Meanwhile the `@anonymous_allowed` will set `user: JWTUser=None` and allow anonymous users to hit the route. The default behavior is `@authentication_required` so you do not need to annotate with this decorator, it is just to help your code be explicit.\n\n## Settings\n\nThere are two settings this package uses to identify the `username` and `user_id` keys in the JWT payload, they are by default:\n\n```python\n{\n  'JWT_USER_ID': 'id',\n  'JWT_USER_NAME': 'username',\n}\n```\n\nIf your JWT uses some other kind of key, override these keys when you instantiate your component:\n\n```python\nfrom apistar_jwt.token import JWT\n\ncomponents = [\n  JWT({\n    'JWT_USER_ID': 'pk',\n    'JWT_USER_NAME': 'email',\n  })\n]\n```\n\n`JWT_WHITE_LIST` allows you to specify a list of route functions that will not require JWT authentication. This is useful if you have setup a default authentication policy but want to open up certain routes, especially ones that might be in third party packages or in apistar itself like the schema docs.\n\n```python\nfrom apistar_jwt.token import JWT\n\ncomponents = [\n  JWT({\n    'JWT_WHITE_LIST': ['serve_schema', 'home'],\n  })\n]\n```\n\nIn this instance, the `serve_schema` and `home` Routes will not require JWT authentication.\n\n`JWT_ALGORITHMS` is related to the algorithms used for decoding JWTs. By default we only use 'HS256' but JWT supports passing an array of [supported algorithms](https://pyjwt.readthedocs.io/en/latest/algorithms.html#digital-signature-algorithms) which it will sequentially try when attempting to decode.\n\n```python\nfrom apistar_jwt.token import JWT\n\ncomponents = [\n  JWT({\n    'JWT_ALGORITHMS': ['HS256', 'RSA512'],\n  })\n]\n```\n\n`JWT_AUTHORIZATION_PREFIX` is the string that comes before the token in the Authorization header. Defaults to 'bearer' (the header is not case sensitive)\n\n```python\nfrom apistar_jwt.token import JWT\n\ncomponents = [\n  JWT({\n    'JWT_AUTHORIZATION_PREFIX': 'jwt'\n  })\n]\n```\n\n`JWT_SECRET` is a long, randomized, secret key that should never be checked into version control.\n\n```python\nfrom apistar_jwt.token import JWT\n\ncomponents = [\n  JWT({\n    'JWT_SECRET': 'QXp4Z83.%2F@JBiaPZ8T9YDwoasn[dn)cZ=fE}KqHMJPNka3QyPNq^KnMqL$oCsU9BC?.f9,oF2.2t4oN?[g%iq89(+'\n  })\n]\n```\n\nFor all other settings, use `JWT_OPTIONS` key which will pass them along to the underlying [PyJWT](https://pyjwt.readthedocs.io/en/latest/usage.html#registered-claim-names) library when decoding.\n\n```python\nfrom apistar_jwt.token import JWT\n\ncomponents = [\n  JWT({\n    'JWT_OPTIONS': {\n      'issuer': 'urn:foo',\n      'audience': 'urn:bar',\n      'leeway': 10,\n    },\n  })\n]\n```\n\nQuick rundown of the options:\n\n`audience` is the urn for this applications audience, it must match a value in the `aud` key of the payload. [Read more about audience claim](https://pyjwt.readthedocs.io/en/latest/usage.html#audience-claim-aud).\n\n`issuer` is the urn of the application that issues the token, it must match a value in the `iss` key of the payload. [Read more about the issuer claim](https://pyjwt.readthedocs.io/en/latest/usage.html#issuer-claim-iss)\n\n`leeway` is the number of seconds of margin an expiration time claim in the past will still be valid for.\n\nA fully customized `JWT` component would like like the following:\n\n```python\nfrom apistar_jwt.token import JWT\n\ncomponents = [\n  JWT({\n    'JWT_ALGORITHMS': ['HS256', 'RSA512'],\n    'JWT_USER_ID': 'pk',\n    'JWT_USER_NAME': 'email',\n    'JWT_SECRET': 'QXp4Z83.%2F@JBiaPZ8T9YDwoasn[dn)cZ=fE}KqHMJPNka3QyPNq^KnMqL$oCsU9BC?.f9,oF2.2t4oN?[g%iq89(+',\n    'JWT_OPTIONS': {\n      'issuer': 'urn:foo',\n      'audience': 'urn:bar',\n      'leeway': 10,\n    },\n    'JWT_WHITE_LIST': ['serve_schema'],\n  })\n]\n```\n\n## Developing\n\nThis project uses [`pipenv`](https://docs.pipenv.org) to manage its development environment, and [`pytest`](https://docs.pytest.org) as its tests runner.  To install development dependencies:\n\n```\npipenv install --dev\n```\n\nTo run tests:\n\n```\npipenv shell\npytest\n```\n\nThis project uses [Codecov](https://codecov.io/gh/audiolion/apistar-jwt) to enforce code coverage on all pull requests.  To run tests locally and output a code coverage report, run:\n\n```\npipenv shell\npytest --cov=apistar_test/\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faudiolion%2Fapistar-jwt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faudiolion%2Fapistar-jwt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faudiolion%2Fapistar-jwt/lists"}