Skip to main content

DRF authentication for Authjs with database adapter

This app is used to integrate Authjs authentication with a Django + DRF project. It can create the DB to be used as with the AuthJs adapter and provides an authentication class based on that. Instead of reauthenticating users with sessions or JWT, it matches the Authjs token sent in the Authorization header with the contents of the database used by Authjs.

Usage

Frontend

In the frontend, use Authjs with a database adapter. In this example, we'll be using the pg adapter for PostgreSQL.

import NextAuth from "next-auth";
import { Pool } from "pg";
import MyProvider from "next-auth/providers/myprovider"; // Example: google

const pool = new Pool({
  host: process.env.DATABASE_HOST,
  user: process.env.DATABASE_USER,
  password: process.env.DATABASE_PASSWORD,
  database: process.env.DATABASE_NAME,
})

export const { auth, handlers, signIn, signOut } = NextAuth({
 providers: [MyProvider],
});

You'll also need to send the session token which each request to the backend.

import { auth } from "@/auth";

const session = await auth();

const data = await fetch("/api/some-protected-endpoint", {
  headers: {
    "Authorization": `Bearer ${session.token}`,
  },
});

Backend

Since we need to adapt the table schema to match authjs's, we recommend using a separate database for the Authjs tables. In the settings.py file, configure a new database connection for Authjs. Be sure to use the same values as the ones passed to the frontend.

# settings.py

import os

...

DATABASES = {
    ...
    "authjs": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.getenv("AUTHJS_DATABASE_NAME"),
        "USER": os.getenv("AUTHJS_DATABASE_USER"),
        "PASSWORD": os.getenv("AUTHJS_DATABASE_PASSWORD"),
        "HOST": os.getenv("AUTHJS_DATABASE_HOST"),
        "PORT": os.getenv("AUTHJS_DATABASE_PORT"),
    },
}

Configure this app to use the created database connection.

# settings.py

...

AUTHJS_DATABASE = "authjs"

Put this package in your INSTALLED_APPS:

# settings.py
INSTALLED_APPS = [
    ...
    "drf_authjs_db_auth",
    ...
]

And run migrations to create the necessary tables (be sure that the database exists beforehand, if not using sqlite):

python manage.py migrate drf_authjs_db_auth --database authjs
python manage.py migrate drf_authjs_db_auth --fake # (avoid warnings about unnapplied migrations)

You can fake both migrations if the database already exists (though we do introduce an extra text column username in the user table, make sure it is present).

Finally, set up the rest framework authentication backend to use Authjs authentication:

# settings.py

REST_FRAMEWORK = {
    ...
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "drf_authjs_db_auth.authentication.AuthJSAuthentication",
        ...
    ],
    ...
}

Getting user data from the backend

If you need additional user information from the backend, you can create a custom user seralizer and read it with authjs's session callback. Example user serializer and view:

from rest_framework import serializers
from django.contrib.auth import get_user_model

UserModel = get_user_model()

class UserDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserModel
        fields = ('pk', 'username', 'email', 'first_name', 'last_name')
        read_only_fields = ('email', 'pk')
from rest_framework.generics import RetrieveAPIView
from rest_framework.permissions import IsAuthenticated

class UserDetailsView(RetrieveAPIView):
    serializer_class = UserDetailsSerializer
    permission_classes = (IsAuthenticated,)

    def get_object(self):
        return self.request.user

For more elaborate examples, check dj_rest_auth's user serializer and user view.

Then, in the frontend, you can append the user data to the session in the NextAuth session callback:

import { auth } from "@/auth";

export const { auth, handlers, signIn, signOut } = NextAuth({
  ...,

  callbacks: {
    async session({ session }) {
      if (session && !session.user?.username) {
        const data = await getUserData(session); // Fetch from your user details endpoint
        session.user.username = data.username;
        session.user.pk = data.pk;
      }

      return session;
    },
  },
})

Contributing

  • Sync packages with uv sync --all-packages;
  • Use mypy to type check;
  • MR to the repository.

Needs doing

  1. Adding an example frontend project (maybe using authjs's example repository for NextJS)
  2. Test behavior and document for different database adapters (Prisma
    • SQLite for example).

Metadata

Release files for drf-authjs-db-auth 0.1.0

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

Source distribution (sdist)

Source distribution for drf-authjs-db-auth 0.1.0
File Size Uploaded Provenance Actions
drf_authjs_db_auth-0.1.0.tar.gz 23.7 kB Without provenance Details for drf_authjs_db_auth-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for drf-authjs-db-auth 0.1.0
File Interpreter ABI Platform Actions
drf_authjs_db_auth-0.1.0-py3-none-any.whl Python 3 none any Details for drf_authjs_db_auth-0.1.0-py3-none-any.whl

Total release size: 31.3 kB

Release files / drf_authjs_db_auth-0.1.0.tar.gz

Download URL drf_authjs_db_auth-0.1.0.tar.gz
Size 23.7 kB
Tags Source
SHA-256 checksum
How to use checksums
bece82dfebfe4aca711740019baf2bc0aa93f6b4f4a1ea9dcecad7deefaf22a4
BLAKE2b-256 checksum
How to use checksums
de85aba9875744264113462cc60334a11109b91215d9c510938659373bc81253
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.15

Release files / drf_authjs_db_auth-0.1.0-py3-none-any.whl

Download URL drf_authjs_db_auth-0.1.0-py3-none-any.whl
Size 7.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7976bcee43716cbbdea09b9d9bdeed215cdc657984c1dc3e12e73cc5890ad2e9
BLAKE2b-256 checksum
How to use checksums
1010b1175a4a7c652c7e8027330af75ad0d9aece89ff92b27f17dc77594c9c2d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.15

Security for drf-authjs-db-auth 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

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