django channels2 token 认证

django channels2 token 认证

  • 通过自定义TokenAuthMiddlewareStack替换AuthMiddlewareStack实现, 我这项目是集成了drf的, token认证方式是drf自带的。
  • authentication.py
from channels.auth import AuthMiddlewareStack
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import AnonymousUser


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

    def __call__(self, scope):
        headers = dict(scope['headers'])
        print(headers)
        if 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
            except Token.DoesNotExist:
                scope['user'] = AnonymousUser()
        return self.inner(scope)



TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner))
  • 修改项目跟settings.py同级的routing.py
from channels.routing import ProtocolTypeRouter, URLRouter
import battle.routing

from battle.authentication import TokenAuthMiddlewareStack


application = ProtocolTypeRouter({
    'websocket': TokenAuthMiddlewareStack(
        URLRouter(
            battle.routing.websocket_urlpatterns
        )
    )
})

[个人博客]http://blog.fenlanli.com

你可能感兴趣的:(django)