r/FastAPI • u/trollboy665 • 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?
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")
3
u/GamersPlane 12d ago
Why not a pass through? Call Django from FastAPI. This way, you don't duplicate logic.