How do you implement authentication and authorization for gRPC services in ASP.NET Core, given gRPC calls don't carry cookies the way browser requests typically do?
Short answer
gRPC authentication commonly uses JWT bearer tokens passed via a custom metadata header (equivalent to an HTTP header) on each call, validated through the same JWT bearer authentication middleware used for REST APIs -- since gRPC runs on top of ASP.NET Core's standard hosting…
Advertisement
AModel answer
gRPC authentication commonly uses JWT bearer tokens passed via a custom metadata header (equivalent to an HTTP header) on each call, validated through the same JWT bearer authentication middleware used for REST APIs -- since gRPC runs on top of ASP.NET Core's standard hosting model, the [Authorize] attribute and policy-based authorization work identically on gRPC service methods as they do on MVC controllers, with the token extracted from call metadata instead of a cookie.
[Authorize]
public class SecureGreeterService : Greeter.GreeterBase {
[Authorize(Policy = "AdminOnly")]
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context) {
var user = context.GetHttpContext().User;
return Task.FromResult(new HelloReply { Message = $"Hello {user.Identity.Name}" });
}
}
// Client attaches the token via call metadata
var headers = new Metadata { { "Authorization", $"Bearer {token}" } };
var reply = await client.SayHelloAsync(request, headers);Real-world example
An internal microservices mesh authenticates gRPC service-to-service calls using JWT bearer tokens issued by a shared identity service, attached as call metadata and validated with the exact same JWT bearer authentication middleware and [Authorize] policies used across the REST APIs in the same solution.
Likely follow-ups
- How does mutual TLS (mTLS) provide an alternative/complementary authentication mechanism for service-to-service gRPC calls?
- How do you propagate authentication context through a chain of gRPC calls (service A calling service B calling service C)?
Related topics