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:
- How do I add the user authentication data (JWT) to API calls that require authentication on the client?
- 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)?
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.The interceptor gets access to a ServiceMethod, which contains a name. So you could check that to only invoke an interceptor on some methods: