question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Interceptor not being called

See original GitHub issue

Hi,

I am trying to create a grpc interceptor that will add a bearer token to the request header on every call if it is available. This is in blazor wasm with pre-rendering and my grpc package versions are 2.37.0

My interceptor code

public class GrpcAuthInterceptor : Interceptor
    {
        private readonly string _apiUrl;
        private readonly string[] _scopes = new[] { "somescope" };
        private readonly AuthenticationStateProvider _authenticationStateProvider;

        public GrpcAuthInterceptor(string apiUrl, AuthenticationStateProvider authenticationStateProvider)
        {
            _apiUrl = apiUrl;
            _authenticationStateProvider = authenticationStateProvider;
        }

        public override AsyncClientStreamingCall<TRequest, TResponse> AsyncClientStreamingCall<TRequest, TResponse>(
            ClientInterceptorContext<TRequest, TResponse> context,
            AsyncClientStreamingCallContinuation<TRequest, TResponse> continuation)
        {
            Console.WriteLine("In add async client streaming call");
            AddCallerMetadata(ref context);
            
            return continuation(context);
        }

        private void AddCallerMetadata<TRequest, TResponse>(ref ClientInterceptorContext<TRequest, TResponse> context)
            where TRequest : class
            where TResponse : class
        {
            Console.WriteLine("In add caller metadata");
            var headers = context.Options.Headers;
            
            var authState = _authenticationStateProvider.GetAuthenticationStateAsync().GetAwaiter().GetResult();
            var user = authState.User;
            Console.WriteLine("grabbing a user");
            var token = user.Claims.FirstOrDefault(a => a.Type == "access_token")?.Value;
            Console.WriteLine($"{user.Claims.Select(_ => _.Value)}");
            // Call doesn't have a headers collection to add to.
            // Need to create a new context with headers for the call.
            if (headers == null)
            {
                headers = new Metadata();
                var options = context.Options.WithHeaders(headers);
                context = new ClientInterceptorContext<TRequest, TResponse>(context.Method, context.Host, options);
            }

            // Add caller metadata to call headers
            headers.Add("grpc-internal-encoding-request", "gzip");

            Console.WriteLine("adding token");
            headers.Add("Authorization", $"Bearer {token}");
        }
    }

I add the interceptor to DI with this line of code

services.AddSingleton(new GrpcAuthInterceptor(apiUrl, services.BuildServiceProvider().GetService<AuthenticationStateProvider>()));

I add the interceptor to the grpc client like

serviceCollection
                .AddGrpcClient<SomeClient.Client>("clientname", options =>
                {
                    options.Address = new Uri(apiUrl);
                })
                .AddInterceptor<GrpcAuthInterceptor>()
                .ConfigureChannel(options =>
                {
                    options.ServiceConfig = new ServiceConfig { MethodConfigs = { defaultMethodConfig } };
                })
                .ConfigurePrimaryHttpMessageHandler(() =>
                {
                    var handler = new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler());
                    return handler;
                });

I can see the constructor of the interceptor being called but no other methods are called. Any help is appreciated thank you!

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:15 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
JamesNKcommented, Apr 30, 2022

It’s not a generic way to modify the headers asynchronously in an interceptor, but solves the specific use case of setting up the call credentials.

Although it is called “AddCallCredentials”, you can set whatever headers you want in it with async + DI.

1reaction
RonPeterscommented, Apr 29, 2022

@CoryKoehler FYI, prior to 2.46.0-pre1, this is the accepted way of doing it: (https://github.com/grpc/grpc-dotnet/issues/1682#issuecomment-1097812953)

The problem is you have to instantiate a new DI scope every time, which has its own problems. But at least it gets you there. I’m using Blazor WASM as well.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Interceptor not intercepting http requests (Angular 6)
In my case interceptor wasn't getting involved for service calls because I had imported HttpClientModule multiple times, for different modules.
Read more >
That's why your Angular Interceptor may NOT WORK! 😥 [5 ...
EDIT: This problem does not occur when you import HttpClientModule only ONCE in the AppModule or CoreModule (and import the CoreModule into ...
Read more >
Interceptor in component not working? : r/angular
So I created a HttpInterceptor. The problem when I add it on the app.module its working, but when I add it as a...
Read more >
HTTP - Intercept requests and responses
This no-op interceptor calls next.handle() with the original request and returns the observable without doing a thing. The next objectlink. The next object ......
Read more >
Angular Basics: Intro to Angular Interceptors
Interceptors can help provide a great user experience in your Angular app for HTTP requests. Let's get started!
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found