Skip to main content

Django Ninja OAuth2

Django Ninja OAuth2 package enables support of OAuth2 / OpenID Connect "Authorization Code Flow" for your swagger documentation.

Requirements

  • Python >= 3.10
  • django >= 3.1
  • pydantic >= 2.0
  • Django-Ninja >= 1.1.0

Installation

pip install django-ninja-oauth2

After installation, change settings.py file. Locally it only worked with None. On a real domain it should work with "same-origin-allow-popups".

# in <myapp>/settings.py
SECURE_CROSS_ORIGIN_OPENER_POLICY = None  # or "same-origin-allow-popups"

Usage

Initialize NinjaAPIOAuth2 wherever you would initialize the original Django Ninja api.

Set your authorization, token and public key url

By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error.

If auto_error is set to False, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be None.

from ninja_oauth2 import NinjaAPIOAuth2, SwaggerOAuth2
from ninja_oauth2.security.oauth2 import OAuth2AuthorizationCodeBearer

oauth2 = OAuth2AuthorizationCodeBearer(
    authorization_url="https://test.com/auth/realms/<realm>/protocol/openid-connect/auth",
    token_url="https://test.com/auth/realms/<realm>/protocol/openid-connect/token",
    public_key_url="https://test.com/auth/realms/<realm>",
    auto_error=True # Default True
)

api = NinjaAPIOAuth2(
    docs=SwaggerOAuth2(
        auth={"clientId": "<client_id>"}
    ),
    auth=oauth2) # Use auth for all endpoints, optional

@api.get("/add", tags=["Main"], auth=oauth2) # Use auth for specific endpoint
def add(request, a: int, b: int):
    return {"result": a + b}

If you want to check the encoded jwt token against some condition, you can extend the OAuth2AuthorizationCodeBearer in the following way:

from typing import Optional, Any
from django.http import HttpRequest
from ninja_oauth2 import NinjaAPIOAuth2, SwaggerOAuth2
from ninja_oauth2.security.oauth2 import OAuth2AuthorizationCodeBearer

class MyOAuth2(OAuth2AuthorizationCodeBearer):
    # token_info returns the encoded jwt token
    def authenticate(self, request: HttpRequest, token_info: dict) -> Optional[Any]:
        if token_info["resource_access"]["<clien_id>"]["roles"] == "admin":
            return token_info
        # Otherwise it will return a 401 unauthorized

        
oauth2 = MyOAuth2(
    authorization_url="https://test.com/auth/realms/<realm>/protocol/openid-connect/auth",
    token_url="https://test.com/auth/realms/<realm>/protocol/openid-connect/token",
    public_key_url="https://test.com/auth/realms/<realm>"
)

api = NinjaAPIOAuth2(
    docs=SwaggerOAuth2(
        auth={"clientId": "<client_id>"}
    ),
    auth=oauth2)

Metadata

Release files for django-ninja-oauth2 0.1.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-ninja-oauth2 0.1.6
File Size Uploaded
django_ninja_oauth2-0.1.6.tar.gz 47.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for django-ninja-oauth2 0.1.6
File Interpreter ABI Platform
django_ninja_oauth2-0.1.6-py3-none-any.whl Python 3 none any Details

Total release size: 57.2 kB

Release files / django_ninja_oauth2-0.1.6.tar.gz

Download URL django_ninja_oauth2-0.1.6.tar.gz
Size 47.7 kB
Tags Source
SHA-256 checksum
How to use checksums
6877c4b89139b4118f74ee2f90fe532e9807811d272f4c13ff0f9066967d18c3
BLAKE2b-256 checksum
How to use checksums
f1ef6244f534b026580d8db27e87f42a8786aa33cf8323f57c88bd6d48526ce5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.6.6

Release files / django_ninja_oauth2-0.1.6-py3-none-any.whl

Download URL django_ninja_oauth2-0.1.6-py3-none-any.whl
Size 9.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
00cb672a03e9321f2835e4324be91a6230ad2a5a95aea76366b0092e023d88b0
BLAKE2b-256 checksum
How to use checksums
c1c157fd5b1e1c243cbb15eda521e38e954299829014e18513fd723beca63810
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.6.6

Release history Release notifications | RSS feed

This release

0.1.6 This release

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page