5

i have no idea how to connect and authenticate django channels using token authentication because javascript websockets doesnt support passing headers to the server

class TokenAuthMiddleware:
    """
    Token authorization middleware for Django Channels 2
    """

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

    def __call__(self, scope):
        headers = dict(scope['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))

I have found this answer regarding authentication using token but the thing is I don't understand how to pass headers to the server

    token = Token.objects.get(key='175f76fd9b63a9477bf5f9a6f2e9a7f12ac62d65')
            if token.user:
                scope['user'] = token.user
            else:
                scope['user'] = AnonymousUser()
            return self.inner(scope)

TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner))

when ever i manually authenticate users the channels can recognize user and authenticate him

i have tried

def get(request):
        for user in User.objects.all():
            token=Token.objects.get_or_create(user=request.user)
            if token.user:
                print("ok")
            else:
                print("not okay")
            print(token)

adding this function in the same class TokenAuthMiddleware i thought this would work but it's not working so that i can use the token generated to authenticate users

I just want to know is there any way where i can authenticate users using token

john
  • 539
  • 2
  • 9
  • 24
  • Yes you can but as you already noticed, you can't pass headers. So you have to pass the token as a query string which isn't safe but that is the main option currently available. Others do the authentication after the initial connection so they can pass the token in the request body which is safer – Ken4scholars Jul 06 '19 at 09:32
  • yes ,please can you elaborate and justify your answer – john Jul 06 '19 at 09:41
  • Check the answers here https://stackoverflow.com/questions/4361173/http-headers-in-websockets-client-api – Ken4scholars Jul 06 '19 at 09:44

0 Answers0