sefidgaran / signalr_client

A Flutter SignalR Client for ASP.NET Core
https://pub.dev/packages/signalr_netcore
MIT License
78 stars 112 forks source link

How to add a query string to the connection? #9

Closed coffeecoding closed 2 years ago

coffeecoding commented 3 years ago

I want my server to identify me, for example by my username. For that I need to pass my username when opening a connection, how to do that?

golovin-igor commented 3 years ago

You can use accessTokenFactory, that adds token parameter to the query:


void createHubConnection() async {
      final httpConnectionOptions = new HttpConnectionOptions(
          accessTokenFactory: () async => 'put_some_token_here',
          logMessageContent: false);

      _hubConnection = HubConnectionBuilder()
          .withUrl(kHubConnectionURL, options: httpConnectionOptions);

      await _hubConnection.start();
     _hubConnection.invoke("tokenTest", args: <Object>[]);
}

then on server you will be able to retrieve token as following:


[HubMethodName("tokenTest")]
public async Task<string> TokenTest()
{
   var request = Context.GetHttpContext().Request;
   if (request.Query.ContainsKey("access_token"))
   {
            string token = request.Query["access_token"].FirstOrDefault();
            //check user token here
   }
}
magnuswikhog commented 2 years ago

Is it possible to do this during the initial connection instead of invoking a method after the connection has already been established?

coffeecoding commented 2 years ago

@magnuswikhog I suppose you use the args array in

await _hubConnection.start();
_hubConnection.invoke("tokenTest", args: <Object>[]);

Does that suffice for your purpose?