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.8
  • 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.5.tar.gz (9.9 kB view details)

Uploaded Source

Built Distribution

django_ninja_oauth2-0.1.5-py3-none-any.whl (8.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: django_ninja_oauth2-0.1.5.tar.gz
  • Upload date:
  • Size: 9.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.4.1 CPython/3.10.6 Linux/6.8.0-45-generic

File hashes

Hashes for django_ninja_oauth2-0.1.5.tar.gz
Algorithm Hash digest
SHA256 c1d3a49b548d9aa1d3eb515944bdc21ecab1e3920febf8ef0fcffb362f838b58
MD5 9f2f33099c2e653eed49fb922ec20c18
BLAKE2b-256 683858c54292d75d767f3e9660746b81e30b5cb734d4052fa97491a409ae4d3a

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for django_ninja_oauth2-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 9f5ced3f43dcad54171f3d7af33eeb269e078c062f50bb333e0ca6381c3bdcfa
MD5 09316f614a2442349a714bad37e27492
BLAKE2b-256 4a1537aa7718b16d80de7ddc2fbab0323dd781ba7f8f6ca08564e4f6cf87884b

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page