如何连接到需要使用flutter进行身份验证的WebSocket?

w80xi6nr  于 4个月前  发布在  Flutter
关注(0)|答案(1)|浏览(56)

我正在尝试在我的flutter应用程序中实现一个WebSocket连接。现在,如果连接是一个非身份验证的连接,它确实可以工作,但如果它需要身份验证,我总是得到这个错误:
Flutter:WebSocketException:连接到“http:myServer.org”未升级到websocket
对于WebSocket,我尝试使用Stomp_dart_client使用以下代码:

_stompClient = StompClient(
      config: StompConfig(
        url: url,
        stompConnectHeaders: {
                      'Connection': 'Upgrade',
             'Upgrade': 'websocket',
          'Authorization': token
          },
        webSocketConnectHeaders: {
            'Connection': 'Upgrade',
             'Upgrade': 'websocket',
            'Authorization': '$token',
            'Content-Type': 'application/json'
          },
        onConnect: (StompFrame frame) {
          emit(const WebsocketState.DataReceived('Connected'));
          debugPrint('----------------                -----------------');
          debugPrint(frame.body);
           debugPrint('----------------                -----------------');
          _subscribeToTopic();
        },
        onWebSocketError: (error) {
          emit(WebsocketState.Error(error.toString()));
           debugPrint('----------------                -----------------');
          debugPrint(error.toString());
           debugPrint('----------------                -----------------');
        },

      ),
    );

    _stompClient!.activate();
  }

字符串
我尝试只设置webSocketConnectHeaders或stompConnectHeaders。
我还尝试使用flutter Web Socket库(dart:io),代码如下:

try {
  _socket = await WebSocket.connect(
  url, 
  headers: {
    'Authorization': token,
  }
  );
  _socket!.listen(
    (data) {
      emit(WebsocketState.DataReceived(data));
      debugPrint('----------------                -----------------');
      debugPrint(data);
      debugPrint('----------------                -----------------');
    },
    onError: (error) {
      emit(WebsocketState.Error(error.toString()));
      debugPrint('----------------                -----------------');
      debugPrint(error.toString());
      debugPrint('----------------                -----------------');
    },
    onDone: () {
      emit(const WebsocketState.Closed());
    },
  );
} catch (e) {
  emit(WebsocketState.Error(e.toString()));
  debugPrint('----------------                -----------------');
  debugPrint(e.toString());
  debugPrint('----------------                -----------------');
}


在这两种情况下,我得到相同的错误,这是服务器显示的I:
2023-11- 21 T15:38:16,234 TRACE [http-nio-8083-exec-1] i.a.c.JwtHandshakeInterceptor:令牌url null 2023-11- 21 T15:38:16,234 TRACE [http-nio-8083-exec-1] i.a.c.JwtHandshakeInterceptor:不应接受连接

6ioyuze2

6ioyuze21#

最重要的东西(我看不到)
确保在传递令牌时,在令牌之前使用Bearer(如果适用)。对于Bearer令牌,它通常看起来像'Authorization': 'Bearer $token'.
也要确保你不需要CORS。因为我在过去遇到过需要用CORS验证的问题,但是如果你不使用令牌,我怀疑你可以在没有CORS的情况下建立连接。

相关问题