shmee
shmee

Reputation: 5101

Sharing authenticated users between Django and django-rest-framework in the same project

I have a Django project that will ultimately consist of three apps. Two of which will be "normal" Django apps, the third is a djangorestframework app. I also plan on creating a desktop client for the project at some point.
I want the rest app to be the only entity communicating with the database. Hence I use requests to communicate with the rest endpoints from the views of the "normal" Django apps and I will do the same for the desktop client.
I want all apps to be accessible only for authenticated users, so I'm using Django's authentication backend.

My question is how to pass on the authenticated user/session from the pure Django apps to the rest endpoints when using requests in the views.

I managed to authenticate on the rest API using request's HTTPBasicAuth, but that requires me to have the user's password at hand in plain text. Sure, I could create a technical user to do these requests. But that would also mean that each and every request would need to go through authentication first and that doesn't feel like the best approach.

I have tried to extract the session cookie from the request object that is provided to the views and pass it on through requests.get, but did not manage to put it into the requests.get call the right way.

As of now, using requests and the established sessions looks like my best bet, especially since that will be the way the desktop client will do things, too. So I'm currently looking for the right way to provide requests.get with the session cookie, but I'm certainly open for better solutions.

Upvotes: 0

Views: 1203

Answers (1)

Navid Zarepak
Navid Zarepak

Reputation: 4208

You should use tokens.

Basically any kind of authentication out of your django project should be managed with secure tokens.

And yes, authentication check should happen everytime you send a request. To make it faster, you can store tokens in memory. (You can use redis or maybe even load your db on memory or ... ) but this is the right and common way to it. Even django does this check everytime using it's builtin functions.

DRF docs recommended some few packages to manage these tokens:

DRF: Third party packages

I used knox for many projects and it's pretty good.

Basically to authenticate your users over all of your projects or microservices, you have to take the token from user, set it as header or ... for your request to the main database or authentication project.

Most of the apps use token in headers which you can simply add to all of your requests calls:

Requests docs: Custom Headers

Upvotes: 1

Related Questions