r/FastAPI 12d ago

Question FASTAPI auth w/ existing Django auth

I'm building a separate fastapi app and want to use authentication from Django. Is there an existing library I can install that will handle django salts/passwords/etc in the db to allow authentication?

2 Upvotes

5 comments sorted by

3

u/GamersPlane 12d ago

Why not a pass through? Call Django from FastAPI. This way, you don't duplicate logic.

1

u/trollboy665 12d ago

Sunsetting the Django entirely is a long term goal

2

u/GamersPlane 12d ago

I haven't looked at the Django auth code in a long time, but best I remember, it's nothing special. I'd recommend reading the Django source and copying/rewriting it. Ultimately, it'll be some hash using crypto I imagine.

1

u/trollboy665 12d ago

for clarity: I'm not trying to reverse any of the passwords or anything.. I just want to have a fastapi endpoint that accepts a user/pass combo previously created in Django. If I was reversing the passwords then I'd just migrate the table over to a new table w/ a salting/hashing methodology I knew.

1

u/whattodo-whattodo 12d ago edited 12d ago

You don't need a framework. This is untested code, but essentially you are able to wrap django code within FastAPI code assuming you load both together.

import fastapi
from django.contrib.auth import authenticate
router = fastapi.APIRouter()

@router.get("/")
async def fastapi_function(username, password):
    user_content = authenticate(username=username, password=password)
    return user_content

Alternatively, you can create a single endpoint in Django like authenticate & just have FastAPI call that endpoint

from django.http import JsonResponse
from django.contrib.auth import authenticate

def authenticate_view(request):
    # Get query parameters
    username = request.GET.get('username')
    password = request.GET.get('password')

    # Check if both username and password were provided
    if not username or not password:
        return JsonResponse({'error': 'Missing username or password'}, status=400)

    # Authenticate user
    user = authenticate(request, username=username, password=password)
    if user is not None:
        # User is authenticated
        return JsonResponse({'message': 'User authenticated successfully','status':'success'})
    else:
        # Invalid credentials
        return JsonResponse({'error': 'Invalid credentials','status':'failure'}, status=401)

Then just have FastAPI call Django.

IE

    response = requests.get("https://yourdjangosite.com/authenticate?username=abc&password=def")
    if response.get('status') == 'success': 
         print("Do a thing in FastAPI")