1

In the following code MetadataUtils.attachHeaders is deprecated (I'm using grpc 1.45.1):

    "request without bearer token should fail" {
        val channel: ManagedChannel = ManagedChannelBuilder.forAddress(address, port)
            .usePlaintext()
            .build()
        var stub = RuleAPIGrpc.newBlockingStub(channel)

        val metadata = Metadata()
        metadata.put(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), "no token ")
        stub = MetadataUtils.attachHeaders(stub, metadata)

        val exception = shouldThrow<StatusRuntimeException> {
            stub.getRule(
                RuleApiProto.GetRuleRequest.newBuilder().build()
            )
        }

        exception.status.code.name shouldBe Code.UNAUTHENTICATED.name
        exception.status.description shouldBe Errors.MISSING_BEARER_TOKEN.name

        channel.shutdown()
    }

I tried to replace it with:

stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata))

But then tests are failing, because of missing AUTH header. When I add the interceptor to the channel:

.intercept(MetadataUtils.newAttachHeadersInterceptor(metadata))

then everything works fine.

And ideas why it doesn't work for the stub?

Pawel
  • 466
  • 1
  • 7
  • 20

1 Answers1

1

Not clear from your description if you are already doing this, but you'll need to use the returned value of the stub from withInterceptors() like this:

stub 
  = stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata));

stub.getRule(...)...

San P
  • 494
  • 3
  • 7
  • In the code snippet I added to my question there is ```stub.getRule(``` – Pawel Apr 20 '22 at 09:49
  • 1
    My point was that `stub.withInterceptors` returns a new value which you need to assign to the variable `stub` and use that in making the call. From your description it is not clear if you are assigning the new value back to `stub`. I can see that you are doing `stub.getRule()` and there is no issue with that. – San P Apr 20 '22 at 23:22