简体   繁体   中英

Custom Authentication in Django Rest Framework

I have a django rest framework application with custom authentication scheme implemented. Now I want to allow external app call some methods of my application. There's an endpoint for external app to login /external-app-login which implemented like this:

class ExternalAppLoginView(views.APIView):
    def post(self, request):
        if request.data.get('username') == EXTERNAL_APP_USER_NAME and request.data.get('password') == EXTERNAL_APP_PASSWORD:
            user = models.User.objects.get(username=username)
            login(request, user)
            return http.HttpResponse(status=200)
        return http.HttpResponse(status=401)

Now I want to add authentication. I implemented it like this:

class ExternalAppAuthentication(authentication.SessionAuthentication):
    def authenticate(self, request):
        return super().authenticate(request)

But authentication fails all the time. What is the correct way to do it? I want to store login/password of external app in variables in application, not in database.

The authentication fails, because it needs to return a registered user in your database to authenticate. However as the user info is all in variables instead of database, the issue arises.

There are more than one ways to overcome this issue. Firstly i would suggest you write the authentication code instead of using return super().authenticate(request) as this would lead you to the real reason of the issue.

Also must give a read to this documentation link, it clears a lot of things regarding authentication.

https://www.django-rest-framework.org/api-guide/authentication/

Now after you have done all that, and you seek ways how to authenticate, then you can try either remote user authentication, or you can check for existing users in your variables and use anonymous user for authentication which resolves the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM