4

I am using this library https://pub.dev/packages/graphql_flutter for graphql in a flutter web application. Below code can be used to get authentication token:

import 'package:graphql_flutter/graphql_flutter.dart';
final HttpLink httpLink = HttpLink(
    'https://api.github.com/graphql',
  );

  final AuthLink authLink = AuthLink(
    getToken: () async => 'Bearer <YOUR_PERSONAL_ACCESS_TOKEN>',
    // OR
    // getToken: () => 'Bearer <YOUR_PERSONAL_ACCESS_TOKEN>',
  );

but how can I put the token in the http header like x-api-key: xxxx when sending requests?

I have tried:

HttpLink link = HttpLink(
    uri: 'https://api.github.com/graphql',
    headers: <String, String>{
      'x-api-key': 'xxxx',
    },
  );

but it gives me the error: The named parameter 'uri' isn't defined. Try correcting the name to an existing named parameter's name, or defining a named parameter with the name 'uri'.

4 Answers 4

2

Base on the answer from @moaid-alrazhy and after checking how AuthLink is working

class CustomAuthLink extends Link {
  CustomAuthLink();

  @override
  Stream<Response> request(Request request, [NextLink? forward]) async* {
    // Some logic here
    final AuthService authService = GetIt.I.get<AuthService>();

    final String? token = authService.token;
    final String deviceID = await DeviceInformation.deviceIMEINumber;

    // TIP: do not forget getting new Request instance!
    final Request req = request.updateContextEntry<HttpLinkHeaders>(
      (HttpLinkHeaders? headers) => HttpLinkHeaders(
        headers: <String, String>{
          // put oldest headers
          ...headers?.headers ?? <String, String>{},
          // and add a new headers
          'Authorization': 'Bearer $token',
          'x-device-id': deviceID,
        },
      ),
    );

    // and "return" new Request with updated headers
    yield* forward!(req);
  }
}
2

Probably if you need to change only the name of the Authentication value you can edit the headerKey param enter image description here

otherwise other parameters can be insert in the "defaultHeaders" fields of the HttpLink object. but I don't know if they can be use for authentication

enter image description here

1
  • defaultHeaders is pretty straight forward and just right for my needs. @SonOfGillas please, use code snippets. In case the images are gone, the code will still be visible here.
    – sr9yar
    Commented May 15, 2024 at 15:33
0

Update: base on the answer from @Moaid

import 'package:graphql_flutter/graphql_flutter.dart';

typedef GetHeaders = FutureOr<Map<String, String>> Function();

class CustomAuthLink extends Link {
  CustomAuthLink({
    this.getHeaders,
  });

  final GetHeaders getHeaders;

  @override
  Stream<Response> request(Request request, [NextLink forward]) {
    StreamController<Response> controller;
    Future<void> onListen() async {
      try {
        final Map<String, String> headers = await getHeaders();

        return request.updateContextEntry<HttpLinkHeaders>(
          (_headers) => HttpLinkHeaders(
            headers: <String, String>{
              ...headers,
            },
          ),
        );
      } catch (error) {
        controller.addError(error);
      }

      await controller.addStream(forward(request));
      await controller.close();
    }

    controller = StreamController<Response>(onListen: onListen);

    return controller.stream;
  }
}
-1

you can add it to your HttpLink like this

HttpLink link = HttpLink(
    'https://api.github.com/graphql',
    headers: <String, String>{
      'x-api-key': 'xxxx',
    },
  );

however this was in old versions .. now for more headers your have to write your own CustomAuthLink like

typedef GetHeaders = Future<Map<String, String>> Function();

class CustomAuthLink extends Link {
  CustomAuthLink({
    this.getHeaders,
  }) : super(
          request: (Operation operation, [NextLink forward]) {
            StreamController<FetchResult> controller;

            Future<void> onListen() async {
              try {
                final Map<String, String> headers = await getHeaders();

                operation.setContext(<String, Map<String, String>>{
                  'headers': headers
                });
              } catch (error) {
                controller.addError(error);
              }

              await controller.addStream(forward(operation));
              await controller.close();
            }

            controller = StreamController<FetchResult>(onListen: onListen);

            return controller.stream;
          },
        );

  GetHeaders getHeaders;
}
5
  • I have tried that but it gives me compile error: The named parameter 'uri' isn't defined. Try correcting the name to an existing named parameter's name, or defining a named parameter with the name 'uri'. Commented Apr 21, 2021 at 21:07
  • just remove it , seems they update it. I've update the answer check it. Commented Apr 21, 2021 at 21:11
  • same error happens on header: The named parameter 'headers' isn't defined. Try correcting the name to an existing named parameter's name, or defining a named parameter with the name 'headers'.. Where do you get the API doc for this library? Commented Apr 21, 2021 at 23:46
  • I got this error if I remove headers, Too many positional arguments: 1 expected, but 2 found. Try removing the extra positional arguments, or specifying the name for named arguments.. Commented Apr 21, 2021 at 23:47
  • sorrt the syntax I gave you was in version 1.0.0+1 which indeed had the ma,ed parameters uri and headers about the last one you can check it here pub.dev/documentation/graphql_flutter/latest Commented Apr 22, 2021 at 9:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.