Django请求传输到自定义数据库后端

2024-06-28 15:07:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我的团队正在开发securedjango项目,我们将django请求传输到自定义数据库后端。你知道吗

我们在django中为GSSAPI(SPNEGO)身份验证和委派用户凭据(用于代表用户查询服务器)制作了这样一个算法:

    if 'HTTP_AUTHORIZATION' in request.META:
        kind, initial_client_token = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
        if kind == 'Negotiate':
            server = 'HTTP@server.domain.ru'
            _ignore_result, krb_context = kerberos.authGSSServerInit(server)
            kerberos.authGSSServerStep(krb_context, initial_client_token)
            principal = kerberos.authGSSServerUserName(krb_context)
            _ignore_result = kerberos.authGSSServerStoreDelegate(krb_context)
            conn = psycopg2.connect(
                host='krb5-dbhost',
                user=principal,
                dbname='db',
            )
            cursor = conn.cursor()
            cursor.execute("SELECT version()")
            records = cursor.fetchall()

这在django视图中效果很好。Kerberos服务器可以授权用户并缓存krb5票据,以便凭证委派在psycopg中查询。现在我们需要把它注入django。你知道吗

我们希望继承postgresql数据库后端,如下所示:

from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper


class CustomDatabaseWrapper(DatabaseWrapper):
    def __init__(self, *args, **kwargs):
        super(CustomDatabaseWrapper, self).__init__(*args, **kwargs)

    def get_connection_params(self):
        '''We need to customize this function,
        We need get request here when query processed by web interface,'''
        #.... the source code could be here, but it is not necessary
        return conn_params

所以问题是:“我们怎样才能请求.META(用于获取用户的协商令牌)以及如何将来自web界面的用户请求与管理命令分开

对不起我的英语技能。谢谢你!你知道吗


Tags: django用户self服务器数据库httpserverrequest
1条回答
网友
1楼 · 发布于 2024-06-28 15:07:10

这是中间件和数据库后端,用于缓存django-lrucache-backend

from django.http import HttpResponse
from django.core.cache import caches
from django.conf import settings
import kerberos
import os


class GSSAPIMiddleware(object):
    """GSSAPI Middleware make user auth and cache user token
    and user name. Needed to fix gssstring response like
    spnego protocol says to return response with this string"""

    def process_view(self, request, *args, **kwargs):
        if not settings.GSSAPI_ENABLED_OPTION:
            return None
        unauthorized = False
        if 'HTTP_AUTHORIZATION' in request.META:
            kind, initial_client_token = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
            if kind == 'Negotiate':
                local = caches['local']
                server = settings.GSSAPI_SERVER
                os.environ['KRB5_KTNAME'] = settings.GSSAPI_KEYTAB_PATH
                result, krb_context = kerberos.authGSSServerInit(server)
                kerberos.authGSSServerStep(krb_context, initial_client_token)
                # gssstring = kerberos.authGSSServerResponse(krb_context) FIXME
                principal = kerberos.authGSSServerUserName(krb_context)
                _ignore_result = kerberos.authGSSServerStoreDelegate(krb_context)
                local.set(settings.GSSAPI_USER_PRINCIPAL_KEY, principal)
            else:
                unauthorized = True
        else:
            unauthorized = True
        if unauthorized:
            return HttpResponse('Unauthorized', status=401)
        return None

    def process_request(self, request, *args, **kwargs):
        """function call for every view before Django
        choose witch view would be called. function
        ask user`s browser for Negotiate token"""
        if not settings.GSSAPI_ENABLED_OPTION:
            return None
        unauthorized = False
        if 'HTTP_AUTHORIZATION' in request.META:
            kind, initial_client_token = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
            if kind != 'Negotiate':
                unauthorized = True
        else:
            unauthorized = True
        if unauthorized:
            response = HttpResponse(request, status=401)
            response['WWW-Authenticate'] = 'Negotiate'
            return response
        return None

以及postgresql的数据库后端

from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as DaWr
from django.core.cache import caches
from django.conf import settings


class DatabaseWrapper(DaWr):
    """Custom database backend version for GSSAPI auth
    get user creds from Kerberos and get ticket"""
    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper, self).__init__(*args, **kwargs)

    def get_connection_params(self):
        conn_params = super(DatabaseWrapper, self).get_connection_params()
        if settings.GSSAPI_ENABLED_OPTION:
            local = caches['local']
            principal = local.get(settings.GSSAPI_USER_PRINCIPAL_KEY)
            conn_params['user'] = principal
        return conn_params

相关问题 更多 >