How do I pass an authentication token using the signalR client in Flutter?

Asked

Viewed 131 times

1

I have a flutter mobile app that needs to connect to a signalR hub that needs a touch of authentication. In the angular client I do as follows and function correctly:

this.hubConnection = new signalR.HubConnectionBuilder()
            .withUrl(`${this.apiUrl}chat`, {
                accessTokenFactory: () => userToken
            })
            .build();

Using the flutter client I can’t make it work.

I tried with the following code:

void buildConnection() {
    String hubUrl = AppSettings.API_URL + "/chat";
    var httpOptions = new HttpConnectionOptions(accessTokenFactory: () { return tokenFactory();});
    this._hubConnection = HubConnectionBuilder().withUrl(hubUrl, options: httpOptions).build();
  }

The parameter accessTokenFactory of the object Httpconnectionoptions expecting a Future<String>, then I created one from the token stored in Sharedpreferences:

static Future<String> tokenFactory() async {
    var prefs = await SharedPreferences.getInstance();
    return = prefs.getString("token");
  }

Apparently it validates the token but cannot make the connection by popping the timeout. The question is am I passing the parameter correctly? Is there any better way to do this? I already increased the timeout p 15m and still could not establish a connection.

inserir a descrição da imagem aqui

Note: I have come to the conclusion that it validates the token. Because, if you send a wrong token it returns error 401 - perfect. I tested with an unauthorized hub and connected immediately.

1 answer

0


The way to pass the token is correct, but it can have its syntax improved:

    void buildConnection() {
        String hubUrl = AppSettings.API_URL + "/chat";
        var httpOptions = new HttpConnectionOptions(accessTokenFactory: () async => await tokenFactory());
        this._hubConnection = HubConnectionBuilder().withUrl(hubUrl, options: httpOptions).build();
      }

The timeout problem was linked to the communication protocol, which by default uses websocket. It is the best form of communication, but the flutter client does not change the protocol in case of failure for a new attempt. In my case I had to set the Longpolling protocol.

inserir a descrição da imagem aqui

In short, the code is correct. Only data traffic using the default protocol didn’t work for me, maybe for some reason on the network or server that I haven’t yet discovered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.