Skip to main content

Django Ninja Auth

A one stop shop for all your Django-Ninja Authentication needs. Supports REST authentication with Sessions, Auth Tokens and JWTs.

Fully Customisable to suit your needs.

This repository does not fix any issues in SimpleJWT or django-ninja-jwt. It is intended to build upon the repository and add other forms of authentication on top of just JWTs

Getting Started

Installation

pip install dj-ninja-auth

Setup

NinjaAPI

  1. Create a api.py file in your app directory next to the settings.py and urls.py files.

  2. Add the following lines of code to your api.py

    from ninja_extra import NinjaExtraAPI
    from dj_ninja_auth.controller import NinjaAuthDefaultController
    
    api = NinjaExtraAPI()
    api.register_controllers(NinjaAuthDefaultController)
    
  3. Add the following lines to your urls.py file

    from .api import api
    
    urlpatterns = [
        path("admin/", admin.site.urls),
        path("", api.urls)
    ]
    

This will give you 5 basic endpoints that are not secured and can be called by anyone. The endpoints are

  • /auth/login
  • /auth/logout
  • /auth/password/reset/request
  • /auth/password/reset/confirm
  • /auth/password/change

Authentication

There are 3 controllers that you can register in your api.py file for your application depending on your authentication needs.

Session

The easiest way to use authentication is to use the Session Authentication. Note that the csrf=True kwarg has to be passed in to allow Django Ninja to pass CSRF cookies for validation. You will have to provide your own endpoint to get a CSRF cookie from Ninja.

from ninja.security import django_auth
from dj_ninja_auth.controller import NinjaAuthDefaultController

api = NinjaExtraAPI(auth=[django_auth], csrf=True)
api.register_controllers(NinjaAuthDefaultController)

Token

Since the tokens will be stored in the database, you are required to add the dj_ninja_auth.authtoken app to your INSTALLED_APPS and migrate the database.

from ninja_extra import NinjaExtraAPI
from dj_ninja_auth.authtoken.authentication import AccessTokenAuth
from dj_ninja_auth.authtoken.controller import NinjaAuthTokenController

api = NinjaExtraAPI(auth=[AccessTokenAuth()])
api.register_controllers(NinjaAuthTokenController)

JWT

from ninja_extra import NinjaExtraAPI
from dj_ninja_auth.jwt.authentication import JWTAuth
from dj_ninja_auth.jwt.controller import NinjaAuthJWTController

api = NinjaExtraAPI(auth=[JWTAuth()])
api.register_controllers(NinjaAuthJWTController)

The JWT controller provides 2 additional endpoints for tokens.

  • /auth/refresh
  • /auth/verify

Customisation

Every aspect of the the Schemas and Controllers can be modified to suit your needs.

Schema

Say for example you want to modify the output schema once the user logs in in your app my_app to only display specific fields. In your my_app.schema.py, you can create the following:

from django.contrib.auth import authenticate, get_user_model
from dj_ninja_auth.schema import SuccessMessageMixin, LoginInputSchema

UserModel = get_user_model()

class MyAuthUserSchema(ModelSchema):
    class Meta:
        model = UserModel
        fields = ['id', 'username', 'first_name', 'last_name']

class MyLoginOutputSchema(SuccessMessageMixin):
    user: MyAuthUserSchema
    my_other_value: str

class MyLoginInputSchema(LoginInputSchema):
    @classmethod
    def get_response_schema(cls) -> Type[Schema]:
        return MyLoginOutputSchema

    def to_response_schema(self, **kwargs):
        return super().to_response_schema(my_other_value="foo", **kwargs)

Then in your settings.py, you can specify:

NINJA_AUTH_LOGIN_INPUT_SCHEMA = "my_app.schema.MyLoginInputSchema"

Controller

Say you wanted to add another endpoint to the default auth controller that is an authenticated route and returns the user's details in the schema defined above. In your controller.py:

from ninja_extra import ControllerBase, api_controller, http_get
from ninja_extra.permissions import IsAuthenticated

from .schema import MyAuthUserSchema

class UserController(ControllerBase):
    auto_import = False

    @http_get(
        "/me",
        permissions=[IsAuthenticated],
        response={200: MyAuthUserSchema},
        url_name="get_user",
    )
    def get_user(self):
        return MyAuthUserSchema(user=self.context.request.auth)

@api_controller("/auth", permissions=[AllowAny], tags=["auth"])
class MyNinjaAuthController(
    AuthenticationController,
    PasswordResetController,
    PasswordChangeController,
    UserController
):
    auto_import = False

Then in your api.py, replace the default controller with your custom controller

from ninja_extra import NinjaExtraAPI
from .controller import MyNinjaAuthController

api = NinjaExtraAPI()
api.register_controllers(MyNinjaAuthController)

Release files for dj-ninja-auth 0.1.7

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

Source distribution (sdist)

Source distribution for dj-ninja-auth 0.1.7
File Size Uploaded
dj-ninja-auth-0.1.7.tar.gz 22.6 kB Details

Release files / dj-ninja-auth-0.1.7.tar.gz

Download URL dj-ninja-auth-0.1.7.tar.gz
Size 22.6 kB
Tags Source
SHA-256 checksum
How to use checksums
ddd12dfeac76506ed7e8b72e610a57c5a45596d0201e2928702c255d04a0c502
BLAKE2b-256 checksum
How to use checksums
5add992ef7deda2c36108e7ece9b19b54fecaa0d872b1b3679db2a02c3c11a0a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.10.6

Release history Release notifications | RSS feed

0.1.10

1 release file

0.1.9

1 release file

0.1.8

1 release file

This release

0.1.7 This release

1 release file

0.1.5

1 release file

0.1.4

1 release file

0.1.3

1 release file

0.1.2

1 release file

0.1.1

1 release file

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