【发布时间】:2020-04-25 10:15:51
【问题描述】:
0
我绝不是安全工程师,而且我才刚刚开始我作为 Web 开发人员的旅程。我为我的后端使用一个名为 django 的 python 包,为我的前端使用 react.js。最近我加入了 django-channels ,这是一个让我能够在我的项目中使用 websockets 的包。由于我已经解耦了我的前端和后端,我使用的身份验证的基础是通过令牌(将考虑使用 jwt)。
问题在于,使用 javascript 时,无法通过 websocket 连接发送身份验证标头(或者我告诉你),因此很多人使用 cookie 来发送此身份验证令牌。这是我如何从前端发送令牌的示例 sn-p:
const path = wsStart + 'localhost:8000'+ loc.pathname
document.cookie = 'authorization=' + token + ';'
this.socketRef = new WebSocket(path)
这样做可以让我通过在后端使用定制的中间件提取令牌信息。
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))
然而,这已经引发了某种形式的安全危险信号(或者我告诉你)。
因此,我希望将这个问题扩展到安全资深人士:
- 这种通过 cookie 标头发送令牌身份验证信息的方法安全吗?
- 我实施此方法是否安全?
- 有没有办法进一步确保这一点?
【问题讨论】:
标签: django reactjs websocket token django-channels