Skip to main content

JWT Module for Ellar

Project description

Ellar Logo

Test Coverage PyPI version PyPI version PyPI version

Introduction

JWT utilities module for Ellar.

Installation

$(venv) pip install ellar-jwt

Usage

Import JWTModule:

from ellar.common import Module
from ellar_jwt import JWTModule


@Module(
    modules=[JWTModule.setup(signing_secret_key='my_private_key')]
)
class AuthModule:
    pass

Inject JWTService where its needed as shown below

from ellar_jwt import JWTService
from ellar.di import injectable


@injectable()
class AuthService:
  def __init__(self, jwt_service: JWTService) -> None:
    self.jwt_service = jwt_service

  async def sign_in(self, username: str, password: str) -> t.Dict:
      user = await self.user_service.find_one(username)
      if user.password != credentials.password:
          raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)

      return {
          'access_token': await self.jwt_service.sign_async(user.dict())
      }

JWTModule Setup

There are two ways in config JWTModule

  • setup:

    JWTModule.setup takes some parameters that allows instant configuration of the JWTConfiguration schema required by the JWTService

    For example:

    from ellar.common import Module
    from ellar_jwt import JWTModule
    
    
    @Module(
        modules=[JWTModule.setup(signing_secret_key='my_private_key', issuer='https://google.com')]
    )
    class AuthModule:
        pass
    
  • register:

    JWTModule.register lets you provide JWT configuration in the Ellar application config object using the JWT_CONFIG key. The register function will create a ModuleSetup object that will inject application config to a JWT config factory

    for example:

    # config.py
    import json
    from datetime import timedelta
    
    class DevelopmentConfig:
        JWT_CONFIG = {
            'algorithm':"HS256", # allow_algorithms=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"]
            'leeway': 0, # t.Union[float, int, timedelta]
        
            'signing_secret_key': 'secret', # secret or private key
            'verifying_secret_key': "", # public key
            'audience': None,
        
            'issuer': None,
            'jwk_url': None,
        
            'jti': "jti",
            'lifetime': timedelta(minutes=5), # token lifetime, this will example in 5 mins
        
            'json_encoder':json.JSONEncoder # token lifetime, this will be an example 
        }
    

    In auth/module.py

    from ellar.common import Module
    from ellar_jwt import JWTModule
        
        
    @Module(
        modules=[JWTModule.register_setup()]
    )
    class AuthModule:
        pass
    

JWT Configuration Options

import json
from datetime import timedelta


JWT_CONFIG = {
    'algorithm':"HS256", # allow_algorithms=["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512"]
    'leeway': 0, # t.Union[float, int, timedelta]

    'signing_secret_key': 'secret', # secret or private key
    'verifying_secret_key': "", # public key
    'audience': None,

    'issuer': None,
    'jwk_url': None,

    'jti': "jti",
    'lifetime': timedelta(minutes=5), # token lifetime, this will example in 5 mins

    'json_encoder':json.JSONEncoder # token lifetime, this will be an example 
}
  • lifetime

A datetime.timedelta object is employed to define the validity duration of the tokens. When generating a token, this timedelta value is combined with the present UTC time to establish the default exp claim value for the token.

  • algorithm

The chosen algorithm from the PyJWT library governs the signing and verification procedures for tokens. For symmetric HMAC signing and verification, you have the option to use the following algorithms: HS256, HS384, and HS512. In the case of an HMAC algorithm, the signing_secret_key serves both as the signing and verifying key, rendering the verifying_secret_key setting redundant. On the other hand, for asymmetric RSA signing and verification, you can opt for the following algorithms: RS256, RS384, and RS512. In this scenario, selecting an RSA algorithm mandates configuring the signing_secret_key setting with an RSA private key string. Correspondingly, the verifying_secret_key setting must contain an RSA public key string

  • signing_secret_key

The signing key utilized for signing the content of generated tokens has distinct requirements based on the signing protocol. For HMAC signing, it should be a randomly generated string containing at least as many bits as dictated by the signing protocol. Conversely, an RSA signing should be a string encompassing an RSA private key with a length of 2048 bits or more. As Simple JWT defaults to 256-bit HMAC signing, the signing_secret_key setting automatically takes on the value of your Django project's SECRET_KEY. While this default is practical, developers should modify this setting to a value separate from the Django project's secret key. This adjustment facilitates easier token signing key changes if the key is ever compromised.

  • verifying_secret_key

The verification key is employed to authenticate the contents of generated tokens. In case an HMAC algorithm is indicated by the algorithm setting, the verifying_secret_key configuration is disregarded, and the signing_secret_key setting value will be utilized. However, if an RSA algorithm is designated by the algorithm setting, the verifying_secret_key parameter must be populated with an RSA public key string

  • audience

The audience claim is incorporated into generated tokens and/or verified within decoded tokens. If configured as None, this element is omitted from tokens and isn't subjected to validation.

  • issuer

The issuer claim is added to generated tokens and/or validated within decoded tokens. If configured as None, this attribute is omitted from tokens and isn't subjected to validation.

  • jwk_url

The JWK_URL serves the purpose of dynamically retrieving the required public keys for token signature verification. For instance, with Auth0, you could configure it as 'https://yourdomain.auth0.com/.well-known/jwks.json'. If set to None, this field is omitted from the token backend and remains inactive during validation.

  • leeway

Leeway provides a buffer for the expiration time, which can be defined as an integer representing seconds or a datetime.timedelta object. For further details, please consult the following link: https://pyjwt.readthedocs.io/en/latest/usage.html#expiration-time-claim-exp

  • jti

The claim is designated for storing a token's unique identifier, which is utilized to distinguish revoked tokens within the blacklist application. There might be instances where an alternative claim other than the default "jti" claim needs to be employed for storing this value

  • json_encoder

JSON Encoder class that will be used by the PYJWT to encode the jwt_payload.

API Spec

The JwtService uses PYJWT underneath.

jwt_service.sign(payload: dict, headers: Dict[str, t.Any] = None, **jwt_config: t.Any) -> str

Creates a jwt token for the provided payload. Also, you can override the default jwt config by using passing some keyword argument as a jwt_config

jwt_service.sign_async(payload: dict, headers: Dict[str, t.Any] = None, **jwt_config: t.Any) -> str

Async action for jwt_service.sign

jwt_service.decode(token: str, verify: bool = True, **jwt_config: t.Any) -> t.Dict[str, t.Any]:

Verifies and decodes provided token. And raises a JWTException exception if the token is invalid or expired

jwt_service.decode_async(token: str, verify: bool = True, **jwt_config: t.Any) -> t.Dict[str, t.Any]:

Async action for jwt_service.decode

License

Ellar is MIT licensed.

Download files

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

Source Distribution

ellar_jwt-0.2.5.tar.gz (11.1 kB view details)

Uploaded Source

Built Distribution

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

ellar_jwt-0.2.5-py3-none-any.whl (10.2 kB view details)

Uploaded Python 3

File details

Details for the file ellar_jwt-0.2.5.tar.gz.

File metadata

  • Download URL: ellar_jwt-0.2.5.tar.gz
  • Upload date:
  • Size: 11.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.8

File hashes

Hashes for ellar_jwt-0.2.5.tar.gz
Algorithm Hash digest
SHA256 36cd1b7c4b304658bb0b64e3dc5cbde93ecb3c199080a237a923acae4cc695a8
MD5 5c8981cc5f1a81ab053d25591d40b8a1
BLAKE2b-256 ed603792eaa3abea852875c645e5190c6cf38b498341e28cc30aa09b51a9221f

See more details on using hashes here.

File details

Details for the file ellar_jwt-0.2.5-py3-none-any.whl.

File metadata

  • Download URL: ellar_jwt-0.2.5-py3-none-any.whl
  • Upload date:
  • Size: 10.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.8

File hashes

Hashes for ellar_jwt-0.2.5-py3-none-any.whl
Algorithm Hash digest
SHA256 b79b0300feb9fd9cb828d7d0af7f5b9ffa4a5285ff78037e7a5781ab74cd099a
MD5 ff63c826b890a45dd4f2b003c8b67aa6
BLAKE2b-256 273596ac2d0435e465ab743ea072da0da6223473d26c0fae4d51f61e3940071d

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