首页 > 解决方案 > 如何在多个服务中复制 django 身份验证

问题描述

我们有一个使用 Django 的网络应用程序。我们有如下所述的身份验证系统设置。现在,我们希望将应用程序的某些部分用于独立服务,但我们希望拥有相同的有效令牌/身份验证系统。新服务可能也将使用 Django,所以我想知道这是否可能,或者我必须有哪些选项来实现这种行为。

在我们不在新服务中使用 Django 的情况下,是否有办法仍然使用相同的逻辑来验证两个服务上的请求?

认证系统

现在,我们正在使用rest_framework模块验证请求,更准确地说,是TokenAuthentication类。

这是配置:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
     ...
    'rest_framework',
    'rest_framework.authtoken',
    ...
}

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated'
    ),

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'module.authentications.AuthorizedAuthentication',
    )
}

我们用来授权请求​​的代码:

import logging
from rest_framework.authentication import TokenAuthentication
from rest_framework.exceptions import AuthenticationFailed


class AuthorizedAuthentication(TokenAuthentication):

    def authenticate(self, request):
        response = TokenAuthentication.authenticate(self, request)
        if response is None:
            return None
        return response

为了在视图中进行身份验证,我们执行以下操作:

from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView


class SomeView(APIView):
    permission_classes = (IsAuthenticated,)

编辑

代码不完整所以请不要评论它,我只是复制给你一个关于我们配置的简化示例。

标签: djangodjango-rest-frameworkauthorizationsoa

解决方案


推荐阅读