Add BasicAuthenticationInterceptor for client

This commit is contained in:
Dave Syer
2025-01-06 11:51:01 +00:00
parent f1a8299887
commit f3b0ac11e6
2 changed files with 66 additions and 26 deletions

View File

@@ -3,8 +3,6 @@ package org.springframework.grpc.sample;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.Test;
@@ -18,20 +16,13 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.grpc.client.ChannelBuilderOptions;
import org.springframework.grpc.client.GrpcChannelFactory;
import org.springframework.grpc.client.security.BasicAuthenticationInterceptor;
import org.springframework.grpc.sample.proto.HelloReply;
import org.springframework.grpc.sample.proto.HelloRequest;
import org.springframework.grpc.sample.proto.SimpleGrpc;
import org.springframework.grpc.server.security.GrpcSecurity;
import org.springframework.grpc.test.LocalGrpcPort;
import org.springframework.test.annotation.DirtiesContext;
import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
import io.grpc.Status.Code;
import io.grpc.MethodDescriptor;
import io.grpc.StatusRuntimeException;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@@ -79,22 +70,9 @@ public class GrpcServerApplicationTests {
@Lazy
SimpleGrpc.SimpleBlockingStub basic(GrpcChannelFactory channels, @LocalServerPort int port) {
return SimpleGrpc.newBlockingStub(channels.createChannel("0.0.0.0:" + port,
ChannelBuilderOptions.defaults().withCustomizer((__, channel) -> {
channel.intercept(new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
public void start(ClientCall.Listener<RespT> responseListener,
io.grpc.Metadata headers) {
headers.put(GrpcSecurity.AUTHORIZATION_KEY,
"Basic " + Base64.getEncoder().encodeToString("user:user".getBytes()));
super.start(responseListener, headers);
};
};
}
});
})));
ChannelBuilderOptions.defaults()
.withCustomizer((authority, channel) -> channel
.intercept(new BasicAuthenticationInterceptor("user", "user")))));
}
@Bean