Using Django Session Framework with Token instead of Cookie?

I have a DRF API with secure endpoints that return filtered data depending on whether the user has permission to access.

I have a separate Django OAuth2 provider that contains user models and the values ​​needed to determine that the user has permission to access.

The user must be able to authenticate through the entry point to the DRF API. The API, in turn, receives a token from the Oauth2 provider on behalf of the user and makes several calls to get a list of resources that the user is allowed to access.

Ideally, the DRF API then generates a token and returns it to the user. Whenever a user makes a subsequent request (after logging in) using a token, the API will be able to filter the results by the values ​​returned by calls to the Oauth provider.

The question is how to store this information. This is similar to storing data in an anonymous user session, but using a request header instead of a cookie. I considered dragging and dropping a custom version of django.contrib.sessions.middleware.SessionMiddleware , but I would rather use the installed method instead of writing my own code, as it seems like this should not be a unique problem.

Repeat: is it possible to create an anonymous user session, save it in it and retrieve the session through the request header instead of a cookie?

+4
source share
1 answer

Here is the original SessionMiddleware.process_requestone provided by Django. Let's take a quick look at it.

def process_request(self, request):
    session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
    request.session = self.SessionStore(session_key)

We can clearly see that it explicitly gets the session identifier from cookies using the property SESSION_COOKIE_NAMEdefined in the settings. Therefore, we absolutely must create our own subclass of this SessionMiddlewareand define our own behavior process_request.

, , . :

from django.contrib.sessions.middleware import SessionMiddleware
from django.conf import settings

class CustomSessionMiddleware(SessionMiddleware):
    def process_request(self, request):
         session_key = request.META.get("HTTP_%s" % settings.SESSION_KEY_NAME, None)
         request.session = self.SessionStore(session_key)

, SESSION_KEY_NAME django , . django original SessionMiddleware , requests.session .

. process_response, Set-Cookie.

+1

Source: https://habr.com/ru/post/1624484/


All Articles