Testing from the Client

Let’s test it from a client.

Open chat-cli-client/src/main/java/com/example/chat/ChatClient.java

Implement the Init Auth Service

  1. First, implement initAuthService() method:

Use a ManagedChannelBuilder to create a new ManagedChannel and assign it to authChannel:

// TODO Build a new ManagedChannel
authChannel = ManagedChannelBuilder.forTarget("localhost:9091")
  .usePlaintext()
  .build();
  1. Instantiate a new blocking stub and assign it to authService:
// TODO Get a new Blocking Stub
authService = AuthenticationServiceGrpc.newBlockingStub(authChannel);

Implement authenticate(…)

This method will be called when you start the client and initiate the login process:

  1. Call authService.authenticate(…) to retrieve the token
// TODO Call authService.authenticate(...) and retreive the token
AuthenticationResponse authenticationReponse = authService.authenticate(AuthenticationRequest.newBuilder()
  .setUsername(username)
  .setPassword(password)
  .build());

String token = authenticationReponse.getToken();
  1. Once retrieved the token, call authService.authorization(…) to retrieve all roles, and print them out
// TODO Retrieve all the roles with authService.authorization(...) and print out all the roles
AuthorizationResponse authorizationResponse = authService.authorization(AuthorizationRequest.newBuilder()
  .setToken(token)
  .build());
logger.info("user has these roles: " + authorizationResponse.getRolesList());

Finally, return the token

// TODO Return the token
return token;
  1. If any StatusRuntimeException is caught, handle it, print the error, and then return null
try {
  ...
} catch (StatusRuntimeException e) {
  // TODO Catch StatusRuntimeException, because there could be Unauthenticated errors.
  if (e.getStatus().getCode() == Status.Code.UNAUTHENTICATED) {
    logger.log(Level.SEVERE, "user not authenticated: " + username, e);
  } else {
    logger.log(Level.SEVERE, "caught a gRPC exception", e);
  }
  // TODO If there are errors, return null
  return null;
}