django channels2 token 인증

1525 단어 django
django channels2 token 인증
  • 사용자 정의 Token Auth Middleware Stack을 통해 Auth Middleware Stack을 대체하여 실현했습니다. 제 프로젝트는 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

    좋은 웹페이지 즐겨찾기