Async interceptors (gRPC dart)

Viewed 582

I'm using gRPC generated clients for dart and I need to add Authorization header to every request. I know there's ClientInterceptor but I want to ask if there is any way to call async method in interceptor's method because I have this async method for retrieving token:

static Future<String> getToken() async {
   final CognitoAuthSession session = await Amplify.Auth.fetchAuthSession(
     options: CognitoSessionOptions(getAWSCredentials: true)
   );
   return session.userPoolTokens.idToken;
}
1 Answers

After some more googling I found out that MetadataProvider return FutureOr<void>, so you can call async methods.

Final interceptor's code

class AuthenticationInterceptor extends ClientInterceptor {
  FutureOr<void> _provider(Map<String, String> metadata, String uri) async {
    final token = await AuthenticationService.getToken();
    metadata['Authorization'] = "Bearer $token";
  }

  @override
  ResponseFuture<R> interceptUnary<Q, R>(ClientMethod<Q, R> method, Q request, CallOptions options, invoker) {
    return super.interceptUnary(
        method,
        request,
        options.mergedWith(CallOptions(providers: [_provider])),
        invoker
    );
  }
}

And you can use it like

final client = YourGrpcClient(clientChannel, interceptors: [AuthenticationInterceptor()]);
Related