首页 > 解决方案 > django 登录后我需要什么进行身份验证?

问题描述

我按照以下示例进行操作: https ://docs.djangoproject.com/en/3.0/topics/auth/default/#django.contrib.auth.login

from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        # Redirect to a success page.
        ...
    else:
        # Return an 'invalid login' error message.

此代码似乎没有向客户端返回任何令牌或某种类型,而只是一个重定向。

在 django 检查身份验证的其他代码中,django 检查request.user.is_authenticated. 我需要自己设置吗?

from django.conf import settings
from django.shortcuts import redirect

def my_view(request):
    if not request.user.is_authenticated:
        return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))

要获得装饰器的身份验证,例如@login_required或具有适当的值request.user.is_authenticated,我需要从客户端(ReactJS)发送和接收什么?

标签: djangoauthenticationdjango-authentication

解决方案


您可以返回一个 JsonResponse。

from django.http import JsonResponse

并且登录成功后

return JsonResponse ({
    'token': user.token,
})

推荐阅读