- Problem statement.
- Create empty HTTP-based weather forecast service.
- Create empty gRPC-based authorization service.
- Implement token-based authorization logic in gRPC-based service.
- Add authorization into weather forecast service.
- Testing how authorization works.
This solution demonstrates how to add token-based user authorization, managed by a separate gRPC service, to a mock weather forecast service.
Imagine, you have created a brand new web API service using CLI.
dotnet new webapi --use-controllers --name WeatherForecastService.HttpThis service exposes a single WeatherForecast endpoint accessible to any user.
The goal is to make the endpoint accessible only to users who have a valid token. Additionally, we want to dedicate the authorization logic to the gRPC-based service.
Let's create an empty web API service via CLI by running the following command.
dotnet new webapi --use-controllers --name WeatherForecastService.HttpLet's create an empty gRPC service via CLI by running the following command.
dotnet new grpc --name AuthorizationService.GrpcFirst let's define a new authorization service by adding authz.proto file and reference it in AuthorizationService.Grpc.csproj file.
Next, we need to build the project to have new classes specified in proto automagically generated for us.
dotnet buildNow we need to implement Authorize method declared in authz.proto. Let's create AuthzService.cs file and write Authorize method there. For the sake of simplicity, let's authorize users if the passed authorization token contains valid substring.
Finally we need to map AuthzService in Program.cs file.
Now let's make the weather service call the authorization service on every request and allow or deny access to its endpoint based on the authorization token passed in the request headers.
First we need to copy Protos/authz.proto file from AuthorizationService.Grpc into Protos subdirectory of WeatherForecastService.Http project and reference it in WeatherForecastService.Http.csproj file.
Build the project.
dotnet buildAdd the following NuGet packages.
dotnet add package Grpc.Net.Client
dotnet add package Google.Protobuf
dotnet add package Grpc.Tools
Add inline middleware that validates authorization tokens by calling the authorization service.
We are done! ๐๐๐
Let's run both projects and try calling WeatherForecast endpoint.
First let's call it without a token. As expected, the response code is 401 Unauthorized.
Let's call it again specifying authorization token with valid value. The response code now is 200 Success.
Don't forget to give โญ๏ธ if it was helpful.


