通过cookie头发送令牌认证信息是否安全吗?

问题描述 投票:0回答:1

0

我绝不是安全工程师,而且我刚开始作为Web开发人员的旅程。我在后端使用了一个名为django的python软件包,在前端使用了react.js。最近,我合并了django-channels,这是一个软件包,使我能够在项目中使用websockets。由于我已经分离了前端和后端,因此使用im进行身份验证的基础是通过令牌(将使用jwt进行研究)。

问题是使用javascript时,无法通过websocket连接发送身份验证标头(或这样告诉我),因此许多人都在使用Cookie来发送此身份验证令牌。这是我如何从前端发送令牌的示例片段:

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))

但是这引起了某种形式的安全危险信号(或告诉我)。

因此,我希望将此问题扩展到那里的安全退伍军人:

  1. 通过cookie头发送令牌认证信息的这种方法安全吗?
  2. 我对此方法的实现安全吗?
  3. 是否有办法进一步确保这一点?
django reactjs websocket token django-channels
1个回答
0
投票
  1. 如果您使用的是HTTPS(WSS)Websocket连接,那么通常。
  2. 是,看起来不错
  3. 是,有更好的方法。

(在此域名上创建一个常规HTTP终结点,如果您可以设置一个(正常)django会话cookie,通常这将是您的django登录终结点。这将设置一个HTTPONLY的Cookie(也无法从javascript读取)。这很重要,因此您可能在页面上使用的任何其他js代码都无法读取此值并盗用它。

然后您可以使用https://channels.readthedocs.io/en/latest/topics/sessions.html

注意,当以骄傲的方式运行(仅适用于HTTP)时,还应该在Django设置中设置SESSION_COOKIE_SECURE=True

© www.soinside.com 2019 - 2024. All rights reserved.