jonataslaw / get_server

A backend server that makes it possible to program with Flutter syntax and reuse existing code
Apache License 2.0
476 stars 42 forks source link

The Socket page supports needAuth as true #97

Open speedphp opened 1 year ago

speedphp commented 1 year ago

When GetServer sets WebSocket's GetPage to needAuth: true, JWT authentication will fail and a prompt of "Invalid JWT token!" will be thrown.

GetPage(
   name: Routes.SOCKET,
   page: () => SocketView(),
   binding: SocketBinding(),
   method: Method.ws,
   needAuth: true,
),

Because the Flutter client's GetSocket can only set the url parameter, there is no place to set other headers.

final socket = GetSocket(url);

The websocket implementation of the dart language can support adding userInfo as authentication information in the url parameter,

It's just that the authentication information starts with Basic instead of JWT's Bearer.

Therefore, this modification changed GetServer to add checks for Basic authentication information. Although this Basic information is a JWT authentication Token, this is the minimum modification.

The modifications include:

  1. /lib/src/routes/route.dart#L108, add condition to support tokens starting with Basic.
  2. /lib/src/core/src/utils/token_util.dart#L34, add the code to obtain the Basic authentication token and decode it.
speedphp commented 1 year ago

This way, the GetSocket code can use JWT authentication like this:

  var jwtToken = await LoginService().getJwtToken();
  Get.log("token: $jwtToken");
  var wsUrl = Uri(
      scheme: "ws",
      userInfo: jwtToken,
      host: GetPlatform.isAndroid ? "10.0.2.2" : "127.0.0.1",
      port: 8080,
      path: "/ws");
  Get.log(wsUrl.toString());
  final socket = GetSocket(wsUrl.toString());
  socket.allowSelfSigned = false;
  socket.onOpen(() {
    Get.log("opened");
  });