Skip to main content

JWT validator with public key verification and permission check

Project description

auth_jwt_validator

A simple and secure JWT validation and permission checking package for DRF and GraphQL APIs.


✨ Features

  • 🔐 Verifies JWT tokens using RS256 public keys.
  • ⚙️ Supports dynamic domain configuration to fetch keys from /.well-known/jwks.json.
  • ⚡ Internal caching of public keys to reduce HTTP calls.
  • 🔎 Verifies exp, iat, and kid fields.
  • 🔐 Extracts permissions and user_id from JWT.
  • ✅ Validates required permissions.
  • ✅ Works with DRF: APIView, GenericAPIView, ViewSet.
  • ✅ Supports function-based DRF views.
  • ✅ Supports GraphQL (Graphene).

📦 Installation

pip install auth_jwt_validator

⚙️ Configuration

Before using the validator, configure your auth domain in main settings.py:

from auth_jwt_validator.settings import settings

# Set your user service domain dynamically
settings.set_domain("https://auth.myapp.com")

You can also set custom cache TTL (default is 300 seconds):

configure("https://auth.myapp.com", cache_ttl=600)

🚀 Usage

✅ Option 1: DRF Permission Class (Recommended for class-based views)

Add to your APIView, GenericAPIView, or ViewSet:

from rest_framework.views import APIView
from rest_framework.response import Response
from auth_jwt_validator.drf.permissions import HasJWTAndPermissions

class MyView(APIView):
    permission_classes = [HasJWTAndPermissions]
    required_permissions = ["read_profile"]

    def get(self, request):
        return Response({"user_id": request.user_id})

You can also use this with GenericAPIView:

from rest_framework.generics import GenericAPIView

class MyGenericView(GenericAPIView):
    permission_classes = [HasJWTAndPermissions]
    required_permissions = ["read_profile"]

    def get(self, request):
        return Response({"user_id": request.user_id})

Or inside a ViewSet:

from rest_framework.viewsets import ViewSet

class MyViewSet(ViewSet):
    permission_classes = [HasJWTAndPermissions]
    required_permissions = ["read_profile"]

    def retrieve(self, request, pk=None):
        return Response({"user_id": request.user_id, "profile_id": pk})

✅ Option 2: drf_jwt_required Decorator (for function-based views or custom method handling)

Use it for full control over the method:

from rest_framework.views import APIView
from rest_framework.response import Response
from auth_jwt_validator.decorators.drf import drf_jwt_required

class MyView(APIView):
    @drf_jwt_required(["read_profile"])
    def get(self, request):
        return Response({"user_id": request.user_id})

🧠 Tip: This approach bypasses permission_classes and does everything inline.

✅ With GenericAPIView

from rest_framework.generics import GenericAPIView

class MyGenericView(GenericAPIView):
    @drf_jwt_required(["read_profile"])
    def get(self, request, *args, **kwargs):
        return Response({"user_id": request.user_id})

✅ With ViewSet

from rest_framework.viewsets import ViewSet

class MyViewSet(ViewSet):
    @drf_jwt_required(["read_profile"])
    def retrieve(self, request, pk=None):
        return Response({"user_id": request.user_id, "profile_id": pk})

⚠️ Only use drf_jwt_required when you need per-method control and don’t want to use permission_classes.


🧪 GraphQL Usage (Graphene)

Add the decorator to your GraphQL resolvers:

import graphene
from auth_jwt_validator.decorators.graphql import graphql_jwt_required

class Query(graphene.ObjectType):
    me = graphene.String()

    @graphql_jwt_required(["read_profile"])
    def resolve_me(self, info):
        user_id = info.context.user_id
        return f"Hello user {user_id}"

🔐 JWT Payload Format

JWTs should contain at minimum:

{
  "user_id": "123",
  "permissions": ["read_profile", "edit_profile"],
  "exp": 1712345678,
  "iat": 1712340000,
  "iss": "auth.myapp.com"
}

🛠 Internals

validate_jwt_token(token: str, required_permissions: list[str] | None)

  • Validates signature using public key (with kid)
  • Checks exp, iat, and iss
  • Raises:
    • JWTValidationError
    • PermissionDeniedError

💡 Best Practices

  • Use permission_classes = [HasJWTAndPermissions] for most DRF views.
  • Use drf_jwt_required only for function-based views or fine-grained control.
  • Always call configure(...) once at app startup.
  • Ensure /.well-known/jwks.json is exposed in your user service.

🤝 Contributing

Pull requests welcome!


📄 License

MIT

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

auth_jwt_validator-0.1.8.tar.gz (8.7 kB view details)

Uploaded Source

Built Distribution

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

auth_jwt_validator-0.1.8-py3-none-any.whl (10.3 kB view details)

Uploaded Python 3

File details

Details for the file auth_jwt_validator-0.1.8.tar.gz.

File metadata

  • Download URL: auth_jwt_validator-0.1.8.tar.gz
  • Upload date:
  • Size: 8.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.3

File hashes

Hashes for auth_jwt_validator-0.1.8.tar.gz
Algorithm Hash digest
SHA256 2f70e3e629295df912f3a33959761044d428a56003d18fcf018d74ee519c2a08
MD5 9e12e457d23e6d34bb5f7bafb8b94e55
BLAKE2b-256 e9eb5b3455036648d1b752bc6269872be7e890dcde9702f2fc3e582367eae4d8

See more details on using hashes here.

File details

Details for the file auth_jwt_validator-0.1.8-py3-none-any.whl.

File metadata

File hashes

Hashes for auth_jwt_validator-0.1.8-py3-none-any.whl
Algorithm Hash digest
SHA256 cc8f5f6a54dff574975c1eae64bffc37a88bd5dfa2968d07c316afc283fb0216
MD5 385cd01508c01a2751334e958b854120
BLAKE2b-256 a54e7013fec74bbd5fea69df6484276268d513e2dba7eaa3302b08aca694a5db

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