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).
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:
from channels.db import database_sync_to_async
from django.db import close_old_connections
Token authorization middleware for Django Channels 2
def __init__(self, inner):
self.inner = inner
def __call__(self, scope):
return TokenAuthMiddlewareInstance(scope, self)
def __init__(self, scope, middleware):
self.middleware = middleware
self.scope = dict(scope)
self.inner = self.middleware.inner
async def __call__(self, receive, send):
headers = dict(self.scope["headers"])
if b"authorization" in headers[b"cookie"]:
print('still good here')
cookies = headers[b"cookie"].decode()
token_key = re.search("authorization=(.*)(; )?", cookies).group(1)
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?