Django渠道2:两种身份验证方法

时间:2019-05-14 20:32:29

标签: django django-channels

我如何为Django频道应用程序实现多种身份验证方法? 我的意思是,我有一个基于令牌的auth和一个AuthMiddlewareStack。

我如何维护这两个身份验证,以便为内部应用程序websocket数据使用者/ notify / etc ...管理会话中的django身份验证,并为第三方应用程序采用websocket令牌身份验证?

这是我的routing.py:

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
        URLRouter(
            app.routing.websocket_test
        )
    ),
    "websocket": TokenAuthMiddlewareStack(
        URLRouter([
            app.routing.websocket_test
        ]),
    )
})

谢谢。

1 个答案:

答案 0 :(得分:0)

我解决了实现通用身份验证中间件堆栈(Django Channels的文档)的问题,缺少这些示例。

无论如何,我已经实现了一种混合身份验证堆栈,该堆栈支持:会话,令牌标头和令牌urlpath身份验证方法,可以完美运行:

WSTokenAuthMiddleware.py:

from urllib.parse import parse_qs

from channels.auth import AuthMiddlewareStack
from django.utils import timezone

from rest_framework.authtoken.models import Token
from django.contrib.auth.models import AnonymousUser
from django.db import close_old_connections


class WSTokenAuthMiddleware:
    """
    Token [Querystring/Header] authorization middleware for Django Channels 2
    """

    def __init__(self, inner):
        self.inner = inner

    def __call__(self, scope):
        query_string = parse_qs(scope['query_string']) #Used for querystring token url auth
        headers = dict(scope['headers']) #Used for headers token url auth
        if b'token' in query_string:
            try:
                token_key = query_string[b'token'][0].decode()
                token = Token.objects.get(key=token_key)
                scope['user'] = token.user
                close_old_connections()
            except ApiToken.DoesNotExist:
                scope['user'] = AnonymousUser()
        elif b'authorization' in headers:
            try:
                token_name, token_key = headers[b'authorization'].decode().split()
                if token_name == 'Token':
                    token = Token.objects.get(key=token_key)
                    scope['user'] = token.user
                    close_old_connections()
            except ApiToken.DoesNotExist:
                scope['user'] = AnonymousUser()
        else:
            pass #Session auth or anonymus

        return self.inner(scope)

UniversalAuthMiddlewareStack = lambda inner: WSTokenAuthMiddleware(AuthMiddlewareStack(inner))

Routing.py:

application = ProtocolTypeRouter({
    "websocket": UniversalAuthMiddlewareStack(
        URLRouter(
            ...
        ),
    ),
})