Client Call Credential

Last but not least, there is a special way to apply metadata in the client to outgoing calls, that’s designed specifically to append credentials information. For example, OAuth token might expire, and for each call, if the token expired, you can proactively refresh it, rather than being stuck to a static value.

A Call Credential example is already in the repository. Open chat-cli-client/src/main/java/com/example/chat/grpc/JWTCallCredential.java.

Every time a call takes place, this handler will execute, and you can use MetadataApplier to apply the headers. This method also should not block. If you need to refresh to token, or fetch the token from the network, it should be done asynchronously.

To use the Call Credential, open ChatClient.initChatService(…): 1. Instantiate a JWTCallCredential object with the token 2. Use stub.withCallCredential(…) to decorate the stub

public void initChatServices(String token) {
    logger.info("initializing chat services with token: " + token);

    // TODO Add JWT Token via a Call Credential
    chatChannel = ManagedChannelBuilder.forTarget("localhost:9092")
        .usePlaintext(true)
        .build();

    JwtCallCredential callCredential = new JwtCallCredential(token);
    chatRoomService = ChatRoomServiceGrpc.newBlockingStub(chatChannel)
        .withCallCredentials(callCredential);
    chatStreamService = ChatStreamServiceGrpc.newStub(chatChannel)
        .withCallCredentials(callCredential);
}