Implement user authentication with gRPC

1.5k Views Asked by At

I'm looking to implement simple user authentication with my dart gRPC server + client and am struggling to find samples on how to achieve this properly.

So my problems are the following:

  1. How do I add the user authentication data (JWT) to API calls that require authentication on the client?
  2. How to I handle this data on the server?

I assume that on the client, metadata is the way to go, but is there a way to add the authentication data automatically for each call?

For the server, I assume that interceptors are the way to go, but how do I specify interceptors for specific services only (since not all API calls require authentication)?

1

There are 1 best solutions below

4
On

is there a way to add the authentication data automatically for each call?

You can supply the default CallOptions with the options parameter in the generated client constructor. You can use that to add authorization info to all your calls. If you need to perform async work for each call (for instance, to check if the token is still valid and optionally refresh it), you could add a MetadataProvider which gets invoked for each call.

how do I specify interceptors for specific services only (since not all API calls require authentication)?

The interceptor gets access to a ServiceMethod, which contains a name. So you could check that to only invoke an interceptor on some methods:

extension OnlyInterceptSome on Interceptor {
  Interceptor limitTo(Set<String> endpoints) {
    return (call, method) {
      // Skip the check if we don't care about the method.
      if (!endpoints.contains(method.name)) return null;

      // Invoke the regular interceptor otherwise
      return this(call, method);
    };
  }
}