我想提前告诉你,我正在处理的项目有点混乱,所以我只是在寻找解决方案。
我有一个 Django 应用程序(无 DRF)和一个 CI4 应用程序。我希望身份验证在两个应用程序之间持续存在。基本上,CI4 应用程序是主要的,这是用户进行身份验证的地方。我想使用请求。 Django 应用程序中的会话用于处理身份验证状态。
我让 CI4 应用程序向 Django 应用程序发送 POST 请求,并创建一个请求。身份验证成功后进行会话。
@csrf_exempt
def login_view_endpoint(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = Utilisateur.checkuser(username, password)
if user:
if 'utilisateur' not in request.session:
request.session['utilisateur'] = user.id
print(request.session['utilisateur'])
return HttpResponse('true')
else:
return HttpResponse('false')
else:
# If the request method is not POST, redirect to the login page
return HttpResponse('false')
但问题是,当我测试我想要的流程时,我被重定向到我的 Django 应用程序的“login_page”(我试图删除它),这意味着会话不存在,但身份验证成功,因为我在 CI4 应用程序中得到了真实的响应。
也许我对会话的理解缺乏,或者我遗漏了一些东西,或者该方法完全不起作用,我不知道。
我尝试询问 chatGPT、阅读文档和其他内容,但没有解决方案。我想我需要找一个更了解这个话题的人来帮助我。
我知道这是一种非常迂回的方式,绝对不安全也不是优化的方法。但我现在只是想让它发挥作用。谢谢你
共享会话存储:不要依赖每个应用程序来管理其会话,而是考虑使用两个应用程序都可以访问的共享会话存储。这可以是 Redis 数据库或任何其他快速的键值存储系统。当用户通过 CI4 登录时,将会话令牌和任何相关的用户标识信息存储在此共享存储中。然后 Django 可以检查此存储以验证会话有效性。
确保通信安全:确保 CI4、共享存储和 Django 之间的会话数据通信是安全的。对所有传输中的数据使用 HTTPS,并考虑加密会话数据或使用 JWT 令牌来提高安全性。
Django 自定义身份验证中间件:在 Django 中,实现自定义中间件,用于检查每个请求的共享会话存储中是否存在有效的会话令牌。如果存在有效令牌,则考虑在 Django 中对用户进行身份验证;否则,根据需要重定向或阻止访问。from django.utils.deprecation import MiddlewareMixin import redis # 假设Redis用于会话存储
class SharedSessionMiddleware(MiddlewareMixin):
def __init__(self, get_response=None):
self.get_response = get_response
# Initialize your Redis connection here
self.redis_connection = redis.StrictRedis(host='localhost', port=6379, db=0)
def process_request(self, request):
session_token = request.COOKIES.get('session_token') # Or however you choose to pass the token
if session_token:
user_id = self.redis_connection.get(session_token)
if user_id:
# Here, you would typically set request.user to a user instance
# For simplicity, we're just going to mark the user as authenticated
request.user = {'id': user_id, 'authenticated': True}
return None
# If no valid session, you can redirect or modify the request as necessary
return None
# Remember to add 'YourApp.middleware.SharedSessionMiddleware' to MIDDLEWARE in settings.py