i am by no means a security engineer , and i have barely started my journey as a web developer. Im utilizing a python package known as django for my backend , 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 im 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 .
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 im 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?