Search code examples
authenticationwebsocketdjango-rest-frameworkdjango-channelsdjango-rest-knox

How do you authenticate a websocket connection with Knox token authentication on django channels?


I understand you can write custom authentication middleware to use in django channels 2. This works fine with Django's built-in token authentication but using django-rest-knox tokens is a different story. Knox stores its tokens in an encrypted form so it is not as easy as simply retrieving the user from the database by looking up the token. Please help.


Solution

  • Figured it out!

    from knox.auth import TokenAuthentication
    ...
    knoxAuth = TokenAuthentication();
    user, auth_token = knoxAuth.authenticate_credentials(tokenString.encode(HTTP_HEADER_ENCODING))
    scope['user'] = user
    

    Integrate the above code with: https://gist.github.com/rluts/22e05ed8f53f97bdd02eafdf38f3d60a