2

How would you access the Django authentication framework from a Flask app?

I have a Django app and Flask app running in parallel on a server. Both are hosted behind the same domain, but behind different paths, so they should be able to see each other's cookies.

I'm using Flask to run a simple API microservice, where using Django would be overkill. However, to prevent abuse, I still want Flask to check the request's cookies to see if they're from a user who's still authenticated in the Django application. I don't want to re-implement an authentication framework in Flask.

Access Django settings from inside Flask is relatively simple. I just put something like this at the top of my Flask script to set the path to my Django settings module:

sys.path.insert(0, <path to Django project>)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mydjangoproject.settings")

from django.conf import settings

However, I'm unsure how to update a Flask request handler to pull the correct cookies from a request and verify them with Django's authentication backend. How would I do this?

1
  • Sounds like a good application for using OpenID Connect. I've never implemented it on Django but its ubiquitous enough that it's probably fairly straightforward. Commented Mar 3, 2021 at 22:46

1 Answer 1

2

Digging through the Django interals for the session and authentication middleware, it looks like it's pretty easy to fed Flask's native request instance to them. This seems to do it for me:

from importlib import import_module
from django.conf import settings
from django.contrib.auth.middleware import get_user

engine = import_module(settings.SESSION_ENGINE)
SessionStore = engine.SessionStore
session_key = request.cookies.get(settings.SESSION_COOKIE_NAME)
request.session = SessionStore(session_key)
user = get_user(request)
print(user.is_authenticated)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.