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

时间:2018-10-25 15:30:49

标签: python django gssapi

我的团队正在开发安全的django项目,我们将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-view中效果很好。 Kerberos服务器可以授权用户并缓存krb5-ticket以进行凭据委派,以在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

所以问题是:“如何在get_connection_params()函数中获取request.META(用于获取用户的协商令牌),以及如何将用户从Web界面的请求与管理命令分开。”

对不起,我的英语能力。谢谢!

1 个答案:

答案 0 :(得分:0)

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

cities = City.objects.filter(province__country=country)

和Postgresql的数据库后端

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