2

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)?

enyo
  • 16,269
  • 9
  • 56
  • 73

1 Answers1

2

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);
    };
  }
}
simolus3
  • 286
  • 1
  • 6
  • Ok. That's what I thought. The client side is exactly what I was thinking about. What I don't like about the server side though, is that it makes it really easy to forget a method which wouldn't be authorised then. Of course I can do the opposite, and have an "unauthorized" list instead, but this will become boring quickly. It's also an issue if two methods of two different services have the same name. – enyo Oct 07 '20 at 16:19
  • I don't see how having an "unauthorized" list is bad at all if you want services to be authorized by default. And since an interceptor has to be added to services individually, I don't think that this will be a problem. – simolus3 Oct 07 '20 at 16:42
  • well, my issue is that interceptors aren't added to services but to the server. So all services that I'll create will have to be added to the "unauthorized" list which is going to be the majority of calls. If there was a way to add interceptors to services instead, then I'd be 100% fine with this method. – enyo Oct 07 '20 at 16:46
  • or is there a way that you know of, that you can set interceptors on services? – enyo Oct 08 '20 at 08:03