Jonathan D.
Jonathan D.

Reputation: 179

How to set up login token for graphql/flutter

I have set a login/registration for my app and currently things work with a hard coded token. However, I want to set up dynamic token upon login. Here' the code I have for now.

final AuthLink authLink = AuthLink(
  // getToken: () async => 'Bearer <YOUR_PERSONAL_ACCESS_TOKEN>',
  // OR
  getToken: () async =>
     "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwMzRkNGIyMzkwMDZhM2M4YmYxYWM2ZSIsInVzZXJuYW1lSWQiOiJCbGFjayBQYW50aGVyIiwiaWF0IjoxNjE1OTA2NzY3LCJleHAiOjE2MTY1MTE1Njd9.1xliIkkVdLkOO9AGkWwOdGhBCU18bYh26WPa4YFmEeo",
);

Upvotes: 3

Views: 4484

Answers (2)

ndelanou
ndelanou

Reputation: 921

Using the AuthLink as you did in your code sample:

final httpLink = HttpLink('https://...');
final authLink = AuthLink(getToken: () async => 'Bearer ${await ref.read(tokenProvider)}');
final link = authLink.concat(httpLink);

return GraphQLClient(
  link: link,
  cache: GraphQLCache(),
);

In this code, tokenProvider is a FutureProvider (Riverpod) returning the latest token.This provider is called on every request.

Upvotes: 1

Marcos Maliki
Marcos Maliki

Reputation: 600

You can use any state management for that! For the sake of completion I'll use Riverpod

Step 1: Create a graphql_config.dart file and add this

final StateProvider<String> authTokenProvider =
  StateProvider<String>((_) => '', name: 'tokenP');

final gqlClientProvider = Provider<ValueNotifier<GraphQLClient>>(
 (ref) {
final String token = ref.watch(authTokenProvider).state;

final Link _link = HttpLink('YOUR_GRAPHQL_LINK', defaultHeaders: {
  if (token.isNotEmpty) 'Authorization': 'Bearer $token',
});

return ValueNotifier(
    GraphQLClient(
      link: _link,
      cache: GraphQLCache(store: HiveStore()),
      ),
    );
  },

name: 'gql Provider', );

Step 2: Wrap your MaterialApp (main.dart file) with GraphQLProvider

class MyApp extends ConsumerWidget {
 @override
 Widget build(BuildContext context, ScopedReader watch) {
 final client = watch(gqlClientProvider);

 return GraphQLProvider(
  client: client,
  child: CacheProvider(
    child: MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'YOUR_APP_TITLE',
      ...

Step 3: Update token after successful login. Simply call the Provider and update the token

  context.read(authTokenProvider).state ='YOUR_TOKEN';

PS. I didn't find a good example from the docs so I came up with this

Upvotes: 4

Related Questions