Enforce Role-based Access

Now that we have the User ID and JWT Token in Context, how can we access it from the server stubs? For example, to get the User ID, and check the roles?

Currently, anyone can create a new Chat Room. Let’s lock it down so that only users with the admin role can perform those tasks. In ChatRoomServiceImpl.failBecauseNoAdminRole(…):

  1. Get the Decoded JWT token from context
protected <T> boolean failBecauseNoAdminRole(StreamObserver<T> responseObserver) {
    // TODO Retrieve JWT from Constant.JWT_CTX_KEY
    DecodedJWT jwt = Constant.JWT_CTX_KEY.get();
}
  1. Use it to fetch the associated roles, and then validate if the user has the admin role
protected <T> boolean failBecauseNoAdminRole(StreamObserver<T> responseObserver) {
    // TODO Retrieve JWT from Constant.JWT_CTX_KEY
    DecodedJWT jwt = Constant.JWT_CTX_KEY.get();

    // TODO Retrieve the roles
    AuthorizationResponse authorization = authService.authorization(
        AuthorizationRequest.newBuilder()
            .setToken(jwt.getToken())
            .build());

    // TODO If not in the admin role, return Status.PERMISSION_DENIED
    if (!authorization.getRolesList().contains("admin")) {
      responseObserver.onError(Status.PERMISSION_DENIED.
          withDescription("You don't have admin role").asRuntimeException());
      return true;
    }

    return false;
  }

Restart the server:

$ cd chat-service
$ mvn install exec:java

Then, try in client with a non-admin user:

$ cd chat-cli-client
$ mvn install exec:java
/login [username] | /quit
-> /login rayt
Jun 28, 2017 5:24:35 PM com.example.chat.ChatClient readLogin
INFO: processing login user
password> hello
...
[chat message] | /join [room] | /leave [room] | /create [room] | /list | /quit
rayt-> /create ray-room
[WARNING]
io.grpc.StatusRuntimeException: PERMISSION_DENIED: You don't have admin role
      at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:227)

But, if you try it with the admin user:

$ cd chat-cli-client
$ mvn install exec:java
/login [username] | /quit
-> /login admin
Jun 28, 2017 5:24:35 PM com.example.chat.ChatClient readLogin
INFO: processing login user
password> qwerty
...
[chat message] | /join [room] | /leave [room] | /create [room] | /list | /quit
admin-> /create ray-room
Jun 28, 2017 5:26:42 PM com.example.chat.ChatClient createRoom
INFO: create room: ray-room
Jun 28, 2017 5:26:42 PM com.example.chat.ChatClient createRoom
INFO: created room: ray-room