Websocket jwt认证不断握手和断开连接

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

我在 django 中有这个自定义的 jwt auth-middleware:

class JWTAuthMiddleware:
def __init__(self, inner):
    self.inner = inner

async def __call__(self, scope, receive, send):
    print(": Middleware called")  
    headers = dict(scope['headers'])
    if b'authorization' in headers:
        print(": Authorization header found") 
        try:
            token_name, token_key = headers[b'authorization'].split()
            if token_name == b'Bearer':
                print(": Bearer token found")  
                user = await self.authenticate(token_key.decode())
                if user is not None:
                    print(": User authenticated")
                    scope['user'] = user
        except InvalidTokenError:
            print(": Invalid token")  
            await self.inner(dict(scope, user=None), receive, send)
            return
        except KeyError:
            print(": Invalid token format") 
            await self.send_error(send, "Invalid token format")
            return
    else:
        print(": No authorization header found") 
        await self.inner(dict(scope, user=None), receive, send)

async def authenticate(self, token_key):
    print(": Authenticating user") 
    try:
        secret_key = settings.SECRET_KEY
        decoded_token = decode(token_key, secret_key, algorithms=['HS256'])
        user_id = decoded_token['user_id']
        user = await self.get_user(user_id)
        if user is not None and user.is_authenticated:
            print(": User authenticated successfully")
            return user
    except (InvalidTokenError, KeyError):
        print(": Authentication failed")  
        pass
    return None

@database_sync_to_async
def get_user(self, user_id):
    print(": Retrieving user from database") 
    try:

        return User.objects.get(user_id=user_id)
    except User.DoesNotExist:
        print(": User not found")  
        return None

当我通过邮递员或扑动发出请求时,在用户登录并选择一个组来访问其聊天屏幕后:

void _initializeWebSocket() async {
print("_initializeWebSocket called");
SharedPreferences prefs = await SharedPreferences.getInstance();
String? accessToken = prefs.getString('accessToken');

if (accessToken != null) {
  print("Initializing WebSocket channel");
  channel = IOWebSocketChannel.connect(
    'ws://192.168.1.3:8000/ws/chat/${widget.groupId}/',
    headers: {
      'Authorization': 'Bearer $accessToken',
    },
  );
  print("WebSocket channel initialized successfully");
} else {
  print("Access token not found");
  throw Exception('Access token not found');
}

} 我在 Django 终端中得到这个:

    WebSocket HANDSHAKING /ws/chat/3/ [192.168.1.2:35476]
: Middleware called
: Authorization header found
: Bearer token found
: Authenticating user
: Retrieving user from database
: User authenticated successfully
: User authenticated
WebSocket DISCONNECT /ws/chat/3/ [192.168.1.2:35476]

在颤抖中我得到:

Initializing WebSocket channel

I/flutter (26511): WebSocket channel initialized successfully

E/flutter (26511): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: HttpException: Connection reset by peer, uri = http://192.168.1.3:8000/ws/chat/

这是我在consumers.py中的连接方法:

async def connect(self):
        self.group_id = self.scope['url_route']['kwargs']['group_id']
        self.user = self.scope.get('user')
        if self.user is None:
            print("what")
            await self.close()
            return
        //removed save_user_channel to see if its the problem but it wasn't
        await self.accept()

你能帮我找出握手后 websocket 不断断开的原因吗?

django flutter websocket jwt django-channels
1个回答
0
投票

中间件的

__call__
方法似乎没有随作用域一起运行内部应用程序。尝试返回此:

return await self.inner(scope, receive, send)
© www.soinside.com 2019 - 2024. All rights reserved.