Skip to main content

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

Project description

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)

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

django_ninja_oauth2-0.1.6.tar.gz (47.7 kB view details)

Uploaded Source

Built Distribution

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

django_ninja_oauth2-0.1.6-py3-none-any.whl (9.5 kB view details)

Uploaded Python 3

File details

Details for the file django_ninja_oauth2-0.1.6.tar.gz.

File metadata

  • Download URL: django_ninja_oauth2-0.1.6.tar.gz
  • Upload date:
  • Size: 47.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.6

File hashes

Hashes for django_ninja_oauth2-0.1.6.tar.gz
Algorithm Hash digest
SHA256 6877c4b89139b4118f74ee2f90fe532e9807811d272f4c13ff0f9066967d18c3
MD5 b62082d001edf0704d22719d4563ae89
BLAKE2b-256 f1ef6244f534b026580d8db27e87f42a8786aa33cf8323f57c88bd6d48526ce5

See more details on using hashes here.

File details

Details for the file django_ninja_oauth2-0.1.6-py3-none-any.whl.

File metadata

File hashes

Hashes for django_ninja_oauth2-0.1.6-py3-none-any.whl
Algorithm Hash digest
SHA256 00cb672a03e9321f2835e4324be91a6230ad2a5a95aea76366b0092e023d88b0
MD5 4fd01182ad47949dc7468f02122378ef
BLAKE2b-256 c1c157fd5b1e1c243cbb15eda521e38e954299829014e18513fd723beca63810

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