I am by no means a security engineer , and I have barely started my journey as a web developer. I'm utilizing a Python package known as Django for my backend and react.js for my front end. Recently I have incorporated django-channels, which is a package that gives me the ability to use websockets in my project. Since I have decoupled my front and backends , the basis of authentication I'm using is via tokens (will look into using JWT).
The issue is that with JavaScript , it is not possible to send authentication headers via websocket connection (or so I'm told) , therefore a lot of people are using cookies to send this authentication token instead. Here\s an example snippet of how I am sending the token from my front end:
const path = wsStart + 'localhost:8000'+ loc.pathname
document.cookie = 'authorization=' + token + ';'
this.socketRef = new WebSocket(path)
Doing this allows me to then extract out the token information through utilizing a customized middleware on my backend:
import re
from channels.db import database_sync_to_async
from django.db import close_old_connections
@database_sync_to_async
def get_user(token_key):
try:
return Token.objects.get(key=token_key).user
except Token.DoesNotExist:
return AnonymousUser()
class TokenAuthMiddleware:
"""
Token authorization middleware for Django Channels 2
see:
https://channels.readthedocs.io/en/latest/topics/authentication.html#custom-authentication
"""
def __init__(self, inner):
self.inner = inner
def __call__(self, scope):
return TokenAuthMiddlewareInstance(scope, self)
class TokenAuthMiddlewareInstance:
def __init__(self, scope, middleware):
self.middleware = middleware
self.scope = dict(scope)
self.inner = self.middleware.inner
async def __call__(self, receive, send):
close_old_connections()
headers = dict(self.scope["headers"])
print(headers[b"cookie"])
if b"authorization" in headers[b"cookie"]:
print('still good here')
cookies = headers[b"cookie"].decode()
token_key = re.search("authorization=(.*)(; )?", cookies).group(1)
if token_key:
self.scope["user"] = await get_user(token_key)
inner = self.inner(self.scope)
return await inner(receive, send)
TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner))
However this has raised some form of security red flags (or so I'm told) .
Therefore I wish to extend this questions to the security veterans out there :
- Is this methodology of sending token authentication information via cookie headers safe?
- Is my implementation of this method safe?
- Is there a way to secure this even further?