Home > Mobile >  How to auth in SignalR wih token in Dart?
How to auth in SignalR wih token in Dart?

Time:08-12

How to get access token in SignalR package?

I get access token doing POST request and after that I get the access token. I have a model where I have parsed JSON and have token field.

Auth authFromJson(String str) => Auth.fromJson(json.decode(str));

String authToJson(Auth data) => json.encode(data.toJson());

class Auth {
  Auth({
    this.token,
    this.user,
  });

  final String? token;
  final User? user;

POST request to API to get accesss token which I got succesfully:

   Future<Auth> getToken() async {
        String _email = "admin";
        String _password = "admin";
        Map<String, String> headers = {
          'Content-Type': 'application/json',
          'accept': ' */*'
        };
        final body = {
          'username': _email,
          'password': _password,
        };
        var response = await http.post(
          Uri.parse("http://******/login"),
          headers: headers,
          body: jsonEncode(body),
        );
        print(response.body);
        print(response.statusCode);
        var jsonResponse = jsonDecode(response.body);
         return Auth.fromJson(jsonResponse);
      }

What I have in print in my console:

"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA","user":{}}

After all this stuff I opened docs and found out how SignalR package handle token auth and did the same thing:

 Future<List> fetchLists() async {
 
    final httpConnectionOptions = HttpConnectionOptions(
      accessTokenFactory: () => getToken().then((value) => value.token ?? ''),
    );

    final hubConnection = HubConnectionBuilder()
        .withUrl('http://*****/hub',
            options: httpConnectionOptions)
        .build();
    await hubConnection.start();

So after all of this I got this error [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: 302: Found

it means what I should add access token to each of requests and I do, but still get this error. How can i solve it or may be there is anoher way to add token in HubConnectionBuild?

CodePudding user response:

There is parameter in accessTokenFactory which accept a function and have return type String so make a function which return token . below attached code for your reference-

  _hubConnection = HubConnectionBuilder()
            .withUrl(chaturl,
                
                options: HttpConnectionOptions(
                headers: defaultHeaders,
                   accessTokenFactory: () async => await getToken() //define a function which return token
                    ))
    
              withAutomaticReconnect(retryDelays: [
              20000,
            ]
      ).build();

//get token method

 Future<dynamic> getToken() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    if (sharedPreferences.containsKey("token")) {
      print(sharedPreferences.getString("token"));
      return sharedPreferences.getString("token");
    } else {
      return null;
    }
  }
  • Related