Cerin
Cerin

Reputation: 64719

Using Django to authenticate user from Flask

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?

Upvotes: 2

Views: 1203

Answers (1)

Cerin
Cerin

Reputation: 64719

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)

Upvotes: 2

Related Questions