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...
Quick Start
Installation
pip install pyjwt-wrapper
PyPi page: https://pypi.org/project/pyjwt-wrapper/
Implement your own BackEndAuthenticator
Below is a quick example of how you would implement your own password based authentication. In stead of users being in a dictionary, you would typically connect to a database.
Note: The example below assumes the password is encoded using SHA256. However, when a user enters a password, we will receive it in normal text format which means it also needs to be SHA256 converted in order to compare to the password on record.
You would typically implement in this code in the application/API that handles authentication.
from pyjwt_wrapper import Logger, BackEndAuthenticator, AuthenticationResult, generate_jwt, PASSWORD_SALT
import traceback
import hashlib
class MyBackEndAuthenticator(BackEndAuthenticator):
def __init__(self, logger: Logger=Logger()):
super().__init__(logger=logger)
def authenticate(self, input: dict, request_id: str=None)->AuthenticationResult:
my_hard_coded_users = {
'user1': {
'password': hashlib.sha256('!paSsWord123!{}'.format(PASSWORD_SALT).encode('utf-8')).hexdigest(),
'permissions': ['p1', 'p2'],
'active': True
}
}
result = AuthenticationResult(
success=False,
userid=None,
permissions=list()
)
try:
input_password_hashed = hashlib.sha256('{}{}'.format(input['password'], PASSWORD_SALT).encode('utf-8')).hexdigest()
if input['username'] in my_hard_coded_users:
if my_hard_coded_users[input['username']]['active']:
if input_password_hashed == my_hard_coded_users[input['username']]['password']:
result.success = True
result.userid = input['username']
result.permissions = my_hard_coded_users[input['username']]['permissions']
self.logger.info(message='LOGIN SUCCESS for user "{}"'.format(input['username']), request_id=request_id)
else:
self.logger.error(message='LOGIN FAIL for user "{}" - incorrect password'.format(input['username']), request_id=request_id)
else:
self.logger.error(message='LOGIN FAIL for user "{}" - user not active'.format(input['username']), request_id=request_id)
else:
self.logger.error(message='LOGIN FAIL for user "{}" - user not found'.format(input['username']), request_id=request_id)
except:
self.logger.error(message='EXCEPTION: {}'.format(traceback.format_exc()), request_id=request_id)
return result
Authenticating a user that supplies a username and password
You would also implement in this code in the application/API that handles authentication.
from pyjwt_wrapper.authentication import authenticate_using_user_credentials
# This part would tyically be implemented in a function that receives the username and password
result = authenticate_using_user_credentials(
application_name='my_awesome_app',
username='user1',
password='!paSsWord123!',
request_id='test123',
backend=MyBackEndAuthenticator()
)
# Return the result to the client...
The result may look something like this:
{
'user_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJteV9hd2Vzb21lX2FwcCIsInN1YiI6InVzZXIxIiwiY29udGV4dCI6Im15X2F3ZXNvbWVfYXBwIn0.qylm2cpukiUzCAjeDhO99iTMAWwdjuJKt4Jb2q0np2A',
'access_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJteV9hd2Vzb21lX2FwcCIsInN1YiI6InVzZXIxIiwiYXVkIjoibXlfYXdlc29tZV9hcHAiLCJleHAiOjE2MTYzMTg1MTYsIm5iZiI6MTYxNjIzMjExNiwiaWF0IjoxNjE2MjMyMTE2LCJqdGkiOiJ0ZXN0MTIzIiwicHJtIjpbInAxIiwicDIiXX0.3UXG_fasgaj88ujbltHKqNUgJA1DJX9O6C6-i0Y1cIU',
'request_id': 'test123'
}
You should then use the access_token in every API call you make.
Authorize an API request using the access_token from Authentication
The authorization code is implemented in applications/API that receives requests from the user, which is why each request must include the access_token.
from pyjwt_wrapper.authorization import authorize_token
authorized = authorize_token(
token=result['access_token'],
application_name='my_awesome_app',
request_id='api123'
)
The resulting value from authorized should be True
Implementation
This library can be used in two different contexts:
- During user authentication which will result in a
access_tokenanduser_tokenbeing issues - During API requests, where a previously issued
access_tokenis 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 theapplication_nameparameter. In web applications you could derive this from theHostheader.sub- The subject claim is currently mapped to theusernamein username/passwords authenticationaud- The audience claim which is also mapped to theapplication_nameparameter 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 creationiat- The issued at claim which is set to the Unix timestamp (UTC) of token creationjti- The JWT ID claim which is mapped to therequest_idparameterprm- 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 theBackEndAuthenticatorincluded 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 theapplication_nameparameter. In web applications you could derive this from theHostheader.sub- The subject claim is currently mapped to theusernamein username/passwords authenticationcontext- This value is from theapplication_nameparameter.extra- An optional parameter that will only be present if theBackEndAuthenticatorincluded 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 theaudclaimrequired_permissionwhich is a parameter you pass in based on the type of request. The function will test if this value is present in theprmclaim 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:
- Clone the repository
- Create a Python Virtual Environment
- Install dependencies
- Run the unit tests
- 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
- Create a customizable authorization class
- Create authorization caching feature
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pyjwt-wrapper-0.5.1.tar.gz.
File metadata
- Download URL: pyjwt-wrapper-0.5.1.tar.gz
- Upload date:
- Size: 13.8 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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b91c496838cd4d8f98fc63e1551cb2cdf111766a3e208596bc9e91eb44bc1960
|
|
| MD5 |
05f0d63a75c790908337d2b9a935c312
|
|
| BLAKE2b-256 |
5dc5cdc8f3a7681b3bfc608e0058b977badbeaf6f2e6b6af18ed6263233b0c81
|
File details
Details for the file pyjwt_wrapper-0.5.1-py3-none-any.whl.
File metadata
- Download URL: pyjwt_wrapper-0.5.1-py3-none-any.whl
- Upload date:
- Size: 9.3 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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
568875f927916267a737aeaf22309e4d5866238f096ae1fe64f0bd25b77889bb
|
|
| MD5 |
bfb26c5c8ad324157b37f454dadcae5a
|
|
| BLAKE2b-256 |
07563d998de4b77ef66bb06b5874145b656e0dfb4befae8b63314926770a9d22
|