简体   繁体   English

使用 Django 对来自 Flask 的用户进行身份验证

[英]Using Django to authenticate user from Flask

How would you access the Django authentication framework from a Flask app?您将如何从 Flask 应用程序访问 Django 身份验证框架?

I have a Django app and Flask app running in parallel on a server.我有一个 Django 应用程序和 Flask 应用程序在服务器上并行运行。 Both are hosted behind the same domain, but behind different paths, so they should be able to see each other's cookies.两者都托管在同一个域后面,但在不同的路径后面,因此它们应该能够看到彼此的 cookies。

I'm using Flask to run a simple API microservice, where using Django would be overkill.我正在使用 Flask 运行一个简单的 API 微服务,其中使用 Django 将是矫枉过正。 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.但是,为了防止滥用,我仍然希望 Flask 检查请求的 cookies 以查看它们是否来自仍在 Django 应用程序中经过身份验证的用户。 I don't want to re-implement an authentication framework in Flask.我不想在 Flask 中重新实现身份验证框架。

Access Django settings from inside Flask is relatively simple.从 Flask 内部访问 Django 设置相对简单。 I just put something like this at the top of my Flask script to set the path to my Django settings module:我只是在我的 Flask 脚本的顶部放了这样的东西来设置我的 Django 设置模块的路径:

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.但是,我不确定如何更新 Flask 请求处理程序以从请求中提取正确的 cookies 并使用 Django 的身份验证后端验证它们。 How would I do this?我该怎么做?

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.挖掘 session 和身份验证中间件的 Django 内部程序,看起来很容易将 Flask 的本机请求实例提供给它们。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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