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

w80xi6nr  于 2024-01-09  发布在  Flutter
关注(0)|答案(1)|浏览(340)

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

  1. _stompClient = StompClient(
  2. config: StompConfig(
  3. url: url,
  4. stompConnectHeaders: {
  5. 'Connection': 'Upgrade',
  6. 'Upgrade': 'websocket',
  7. 'Authorization': token
  8. },
  9. webSocketConnectHeaders: {
  10. 'Connection': 'Upgrade',
  11. 'Upgrade': 'websocket',
  12. 'Authorization': '$token',
  13. 'Content-Type': 'application/json'
  14. },
  15. onConnect: (StompFrame frame) {
  16. emit(const WebsocketState.DataReceived('Connected'));
  17. debugPrint('---------------- -----------------');
  18. debugPrint(frame.body);
  19. debugPrint('---------------- -----------------');
  20. _subscribeToTopic();
  21. },
  22. onWebSocketError: (error) {
  23. emit(WebsocketState.Error(error.toString()));
  24. debugPrint('---------------- -----------------');
  25. debugPrint(error.toString());
  26. debugPrint('---------------- -----------------');
  27. },
  28. ),
  29. );
  30. _stompClient!.activate();
  31. }

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

  1. try {
  2. _socket = await WebSocket.connect(
  3. url,
  4. headers: {
  5. 'Authorization': token,
  6. }
  7. );
  8. _socket!.listen(
  9. (data) {
  10. emit(WebsocketState.DataReceived(data));
  11. debugPrint('---------------- -----------------');
  12. debugPrint(data);
  13. debugPrint('---------------- -----------------');
  14. },
  15. onError: (error) {
  16. emit(WebsocketState.Error(error.toString()));
  17. debugPrint('---------------- -----------------');
  18. debugPrint(error.toString());
  19. debugPrint('---------------- -----------------');
  20. },
  21. onDone: () {
  22. emit(const WebsocketState.Closed());
  23. },
  24. );
  25. } catch (e) {
  26. emit(WebsocketState.Error(e.toString()));
  27. debugPrint('---------------- -----------------');
  28. debugPrint(e.toString());
  29. debugPrint('---------------- -----------------');
  30. }


在这两种情况下,我得到相同的错误,这是服务器显示的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的情况下建立连接。

相关问题