2
votes

I have a question regarding authentication. Let's say i have a Django app where i only want users from an another user-database API to login. Is it possible to use Django's session authentication, but without having to create them as a user in Django's user backend?

I'm using Django's rest framwork.



Auth flow:

  1. Post a request to another user-database API with username and password. Status code 200 if user exists.
  2. Use Django's (if posssible) session authentication to manage this new session, so the user doesn't have to login on every refresh, but not be logged in permanently either.
  3. Be able to logout, too

I know about the different kinds of auth for django-rest-framwork but they all seem to wanna have a user created in their backend.


Using

  • django 1.11.3
  • djangorestframework 3.7.7
1

1 Answers

1
votes

serializers.py

LoginSerializer(serializers.Serializer):
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True)

views.py

import requests
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions
from rest_framework import exceptions
from django.contrib.auth import authenticate, login
from .serializers import LoginSerializer

class LoginView(APIView):
    permission_classes = (permissions.AllowAny, )
    serializer_class = LoginSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        data = {'username': serializer.validated_data['username'], 'password':serializer.validated_data['password']}
        status = requests.post("{external_api_url}", data=data)
        if status.status_code == 200:
            user = authenticate(serializer.validated_data['username'])
            if user:
                login(request, user)
                return Response({'detail': 'OK'})
        else:
            raise exceptions.AuthenticationFailed('Login Error')