Home > Enterprise >  Adding a token in GraphQL
Adding a token in GraphQL

Time:01-17

The algorithm of the application is as follows:

  1. The user registers \ authorizes and receives a token at the output.
  2. This token must be sent in all subsequent requests.

What I did:

void main() async{
 WidgetsFlutterBinding.ensureInitialized();
 final _sessionDataProvider = SessionDataProvider();
 String? s = await _sessionDataProvider.getSessionId();
 final HttpLink httpLink = HttpLink("https://my_api.ru/graphql/", defaultHeaders: {"Authorization": "Bearer ${s}"});
 ValueNotifier<GraphQLClient> client = ValueNotifier(GraphQLClient(
     link: httpLink, cache: GraphQLCache(store: InMemoryStore())));
 var app  = GraphQLProvider(client: client, child: MyApp());
 runApp(app);
}

here I initialized GraphQl and passed the token to defaultHeaders. If it is passed in pre-written text, then everything works, but in my case I get the token after GraphQL initialization. Help how can I fix this

CodePudding user response:

Use AuthLink. getToken will be called for every request.

  final HttpLink httpLink = HttpLink(
    '<graphql-url>',
  );

  final AuthLink authLink = AuthLink(
    getToken: () async { 
      // TODO
      return 'Bearer <token>';
    }
  );

  final Link link = authLink.concat(httpLink);
  • Related