Skip to main content

An easy to use wrapper around PyJWT for authentication and authorization.

Project description

An easy to use wrapper around PyJWT for authentication and authorization.

Note: The development is still in an early stage, and therefore documentation should improve over time. Right now, only some basic concepts are covered.

Why this may be useful

PyJWT is a really solid library and a very useful tool for creating and using JSON Web tokens (JWT) in applications. Check out https://jwt.io/ for more info around JSON Web Tokens.

This library is a wrapper around PyJWT that creates a standard access token and user token.

Note: Refresh tokens to come soon...

Implementation

This library can be used in two different contexts:

  1. During user authentication which will result in a access_token and user_token being issues
  2. During API requests, where a previously issued access_token is validated and some tests are done before the request is authorized.

For the authentication portion, you will probably implement this library at the authentication API end-point.

For authorization, you would typically implement this library in your API Gateway or proxy server in the authorization leg.

Authentication

You will still need to implement the actual method of authentication. This process is facilitated by the BackEndAuthenticator class which you need to extend with your own implementation of the authenticate method.

The authenticate method returns a AuthenticationResult which contains enough information to finally construct the dictionary that will hold the access token and user token.

The JSON Web Token (generated from pyjwt_wrapper.authentication)

Thus far, this library only support username and password authentication in a function called authenticate_using_user_credentials (name may change in future).

Access Token

The access token is typically used by one application that is requesting resources from another application to authorize the first application. The authorization is usually done by some kind of a proxy in front of the second application. A web page rendered in a user's web browser that requests some data from an application hosted on the Internet is a typical example of this setup. In this case the web page will include the access_token with each request to the application API. Each request has to pass the authorization check before the application will respond with the requested data.

There are a number of resources on the Internet that will explain in a lot more detail the mechanics of authorization, but Auth0 has a very good lightweight explanation of how the process would work.

The access_token contains the following elements:

  • iss - The issuer claim which is the value of the application_name parameter. In web applications you could derive this from the Host header.
  • sub - The subject claim is currently mapped to the username in username/passwords authentication
  • aud - The audience claim which is also mapped to the application_name parameter at the moment.
  • exp - The expiration time claim which is the Unix timestamp (UTC) after which this token is no longer considered valid.
  • nbf - The not before claim which is set to the Unix timestamp (UTC) of token creation
  • iat - The issued at claim which is set to the Unix timestamp (UTC) of token creation
  • jti - The JWT ID claim which is mapped to the request_id parameter
  • prm - A list of permission names (strings) that was valid for the user at the time of authentication. This may be useful in some front-end application to decide which components to render. For example, only provide administrator controls/components to the users that have admin rights.
  • extra - An optional parameter that will only be present if the BackEndAuthenticator included extra data to include in the token. This is a standard dictionary and should only contain primitives.

User Token

The user token (also known as the ID token) contains basic user profile information.

The access_token contains the following elements:

  • iss - The issuer claim which is the value of the application_name parameter. In web applications you could derive this from the Host header.
  • sub - The subject claim is currently mapped to the username in username/passwords authentication
  • context - This value is from the application_name parameter.
  • extra - An optional parameter that will only be present if the BackEndAuthenticator included extra data to include in the token. This is a standard dictionary and should only contain primitives.

Authorization (as implemented by from pyjwt_wrapper.authorization)

During the authorization phase, PyJWT is used for the general token validation.

In addition, the authorize_token takes a number of other parameters used in the authorization process:

  • application_name, which will be used to validate the aud claim
  • required_permission which is a parameter you pass in based on the type of request. The function will test if this value is present in the prm claim values.

Logging

The library utilizes the standard Python logging framework and by default will use a STDOUT log handler.

Most functions takes a logger parameter which implements the Logger class. If you create your own handler, just create it yourself and initialize Logger with your handler.

Example:

from pyjwt_wrapper import Logger
import logging

fh = logging.FileHandler('spam.log')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

my_logger = Logger(logging_handler=fh)

# later usage...
from pyjwt_wrapper.authentication import authenticate_using_user_credentials

auth_result = authenticate_using_user_credentials(
    application_name='my_aoo',
    username='some_user@example.tld',
    password='the world strongest password',
    logger=my_logger,
)

# Use the logger in your own app:
my_logger.info(message='This is a test', request_id='some-request-reference...')

Testing from Source

Basic steps:

  1. Clone the repository
  2. Create a Python Virtual Environment
  3. Install dependencies
  4. Run the unit tests
  5. Get teh coverage reports

The steps above can all be summarized in the following list of Unix commands (bash or zsh):

# Clone the repository
git clone https://github.com/nicc777/pyjwt-wrapper.git

cd pyjwt-wrapper

# Create a Python Virtual Environment
python -m venv venv

. venv/bin/activate

# Install dependencies
pip install pyjwt coverage

# Run the unit tests
coverage run --source ./src -m unittest discover

# Get teh coverage reports
coverage report -m

To Do

  • Creation of Refresh Tokens
  • Managing of Refresh Tokens

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyjwt-wrapper-0.5.0.tar.gz (10.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyjwt_wrapper-0.5.0-py3-none-any.whl (7.7 kB view details)

Uploaded Python 3

File details

Details for the file pyjwt-wrapper-0.5.0.tar.gz.

File metadata

  • Download URL: pyjwt-wrapper-0.5.0.tar.gz
  • Upload date:
  • Size: 10.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/3.7.3 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.59.0 CPython/3.9.2

File hashes

Hashes for pyjwt-wrapper-0.5.0.tar.gz
Algorithm Hash digest
SHA256 fa565243f21a3b683e20370c4f580a841906e8548fbf5ca97fa1a15b61d15a5f
MD5 7b207989a87f5261341db7cd08799f3c
BLAKE2b-256 74845a2e22bf23d13ea2674ef0474cff55ed27dde400b956e9cdffc2e48e2f0a

See more details on using hashes here.

File details

Details for the file pyjwt_wrapper-0.5.0-py3-none-any.whl.

File metadata

  • Download URL: pyjwt_wrapper-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 7.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/3.7.3 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.59.0 CPython/3.9.2

File hashes

Hashes for pyjwt_wrapper-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e5eac9034941dcf17bbc0e39d04a99f061970f1d6d2d57e058ee2f377057ffa6
MD5 9dc1388adb809c42ae2085c5f0a6fc94
BLAKE2b-256 6ca29011abcc4b6ffef172dc419eea476784047196b64ecc46f4e0161256ae6a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page