当请求来自用户登录的页面时,自动验证DRF。如果外部发出api请求,则请求令牌验证

问题描述 投票:0回答:1

我已经覆盖了自定义用户模型,以便我可以使用电子邮件而不是用户名登录,以便我可以在首次登录时重定向到changepassword。

def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            if user.last_login is None:
                login(request, user)
                return redirect('accounts:change_password')
            else:
                login(request, user)
                return redirect('home')
    else:
        form = AuthenticationForm()

    if request.user.is_authenticated:
        return redirect('home')
    else:
        return render(request, 'login.html', {'form': form})

我已经使用DRF设置了基本的rest API端点

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

当我访问主页时,我需要登录:

@login_required(login_url="/accounts/login/")
def home(request):
    return render(request, 'index.html', {})

我想要做的是使用django.contrib.auth进行身份验证并重定向到主页。

当主页加载时,我想执行一个AJAX调用来显示所有用户。

$.ajax(
    {
        type: "GET",
        url: '/accounts/users/',
        success: function(result){
                 console.log(result);
                }
    });

此调用仅在我已经与我的用户登录时才有效。

如果我在外部访问端点,让我们在Postman中说,它应该让我进行身份验证。

我应该能够使用令牌认证在邮递员外部进行身份验证。


问题:

如何以上述方式将django.contrib.auth身份验证与Django rest_framework令牌身份验证混合使用?我想同时拥有一个Web应用程序和一个REST API。使用django.contrib.auth在Web应用程序中进行身份验证。使用Token对REST API进行身份验证。但是,如果用户已登录Web应用程序,则执行Rest API请求,而无需再次进行身份验证。我可以以某种方式重用Web应用程序会话吗?


已经定制了我的用户模型:https://docs.djangoproject.com/en/2.1/topics/auth/customizing/

看过这个,还没开始实施。我不确定他们如何连接。 https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication



我接受了下面的答案,虽然我同时找到了解决方案。我假设你只能添加一种身份验证方法,但你可以拥有更多。我实际上最终做的是:

'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
)

它就像一个魅力。在我的案例中,IsAuthenticated权限全局应用。在每个端点应用接受的答案

django authentication django-rest-framework
1个回答
1
投票

您始终可以使用任意数量的身份验证方法。除了TokenAuthentication之外,DRF还有SessionAuthentication,它的工作方式类似于原生的Django身份验证。您需要做的就是在设置文件或每个视图中设置globally认证类。

例如,您可以通过这种方式为UserViewSet设置身份验证类。

from rest_framework.authentication import TokenAuthentication, SessionAuthentication


class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
authentication_classes = [TokenAuthentication, SessionAuthentication]

通过这种方式,您的Web客户端可以使用会话进行身份验证,而其他客户端则使用令牌。

© www.soinside.com 2019 - 2024. All rights reserved.