API Gateway in .NET
Introduction
API gateways act as intermediaries that intercept incoming requests and route them to the appropriate destination. They also play a crucial role in authorization, allowing authentication checks to be performed before a request reaches the downstream service.
In microservices architectures, API gateways are essential due to the independent nature of services. Additionally, they enhance security by concealing backend URLs, preventing direct exposure to clients.
Ocelot API Gateway
In ASP.NET, the ocelot NuGet package is used to create API Gateways.
Ocelot is an Open Source .NET Core based API Gateway especially useful for microservices architecture that need unified points of entry into their system. It’s lightweight, fast, scalable and provides routing and authentication among many other features.
The API Gateway should be a standalone ASP.NET core application with a responsibility of just routing requests.
The Ocelot gateway accepts requests as configured in the ocelot.json file and forwards it to its downstream service.
Concepts
The Ocelot API Gateway utilizes various terms, all of which can be defined within a single ocelot.json file, including:
- GlobalConfiguration: The global configuration object mostly contains the BaseUrl that defines the base url of the api gateway.
"GlobalConfiguration": {
"BaseUrl": "http://localhost:5000/"
}- Routes: The Routes are the objects that tell Ocelot how to treat an upstream request.
- Upstream: Upstream requests are url paths that can be accessible by clients can call and can also take {parameters} as query string or routes in the url. For eg
"UpstreamPathTemplate": "/api/soccer/fixtures{params}"{params} can take more as routes such as “/api/soccer/fixtures/1/2” as the request comes in.
- UpstreamHttpMethod: These are http verbs supported by the upstream url. It can be GET, POST, PUT, PATCH, DELETE, HEAD
- Downstream: This property defines the destination url the upstream request routes to
- DownstreamScheme: The scheme of the downstream url path can be http(s)
- DownstreamHostAndPorts: Defines the host and the port
To know more about the configuration, check out the ocelot documentation at https://ocelot.readthedocs.io/en/latest/features/configuration.html
Creating the Ocelot Project
Create a new ASP.NET Core web API application and install the ocelot package
dotnet add package Ocelot --version 23.4.3In the Program.cs class, we need to add the ocelot to the service collection and the middleware. The ocelot.json file is where the configuration for the API gateway resides, and can be configured to read configuration from another file or based on the environment.
builder.Configuration.AddJsonFile("ocelot.json", false, true);
builder.Services.AddOcelot(builder.Configuration)
.AddDelegatingHandler<ApiKeyHandler>();
var app = builder.Build();
await app.UseOcelot();API Gateway configuration with Authentication
In the ocelot.json file, the first scenario defines a route configuration with authentication that requires a bearer jwt token in the Authorization header.
{
"GlobalConfiguration": {
"BaseUrl": "http://localhost:5001"
},
"Routes": [
{
"UpstreamPathTemplate": "/api/soccer/fixtures{params}",
"UpstreamHttpMethod": [
"POST"
],
"DownstreamPathTemplate": "/api/soccer/fixtures{params}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": "5002"
}
],
"AuthenticationOptions": {
"AuthenticationProviderKey": "Bearer"
}
}
]
}With this configuration in place, any POST request that comes to the upstream url (http://localhost:5001/api/soccer/fixtures/1/2) would be forwarded to the downstream url and it also requires bearer authorization.
Claims Transformation
Once a user is authenticated, ocelot can transform claims in to headers, query string and even change downstream path. The several ways to add claims transformation are:
- AddQueriesToRequest
- ChangeDownstreamPathTemplate.
These should be added in Route object in the ocelot.json file. Let’s look at the AddQueriesToRequest and ChangeDownstreamPathTemplate. Check out this link to know more about the several claims transformations available.
AddQueriesToRequest
Ocelot can transform the claims and add it to the query string parameters that gets forward to the downstream
{
"GlobalConfiguration": {
"BaseUrl": "http://localhost:5001"
},
"Routes": [
{
"UpstreamPathTemplate": "/api/soccer/fixtures{params}",
"UpstreamHttpMethod": [
"POST"
],
"DownstreamPathTemplate": "/api/soccer/fixtures{params}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": "5002"
}
],
"AuthenticationOptions": {
"AuthenticationProviderKey": "Bearer"
},
"AddQueriesToRequest": {
"Type": "Claims[Type] > value",
}
}
]
}The code above will look for the Claims[Type] after the user has authorized and it in the query string of the downstream url. So the downstream url should look like this “http://localhost:5001/api/soccer/fixtures?Type=”live”
ChangeDownstreamPathTemplate
Ocelot can also transform claims based on a placeholder in the “DownstreamPathTemplate”.
{
"GlobalConfiguration": {
"BaseUrl": "http://localhost:5001"
},
"Routes": [
{
"UpstreamPathTemplate": "/api/soccer/fixtures",
"UpstreamHttpMethod": [
"POST"
],
"DownstreamPathTemplate": "/{mode}/api/soccer/fixtures",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": "5002"
}
],
"AuthenticationOptions": {
"AuthenticationProviderKey": "Bearer"
},
"ChangeDownstreamPathTemplate": {
"Type": "Claims[mode] > value",
}
},
{
"UpstreamPathTemplate": "/live/api/soccer/fixtures",
"UpstreamHttpMethod": [
"POST",
"GET",
"PUT",
"DELETE",
"PATCH"
],
"DownstreamPathTemplate": "/api/soccer/fixtures",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": "5002"
}
]
},
]
}The code above transforms the downstream url based on the Claims[mode] claims after authentication. The Claims[mode] is substituted with the placeholder in the DownstreamPathTemplate in the {mode} url.
Get Charles’s stories in your inbox
Join Medium for free to get updates from this writer.
Note, the key specified in the ChangeDownstreamPathTemplate must be the same than the placeholder specified in the DownstreamPathTemplate.
The example above also shows another object in the ocelot.json file that defines an upstream url based on the ChangeDownstreamPathTemplate transformation that was done. If the Claims[mode] is live, then it should route to “/api/soccer/live/fixtures” upstream url. The ChangeDownstreamPathTemplate is a preferred header transformation if you want to redirect users to different url based on some claims
Also note that if the Claims[key] does not exists, the transformation would fail.
Handlers
In Ocelot, Delegating Handlers are powerful tools that allow you to inject custom logic into the request/response pipeline before the request is forwarded to the downstream service.
They are similar to middlewares in .NET.
public class ApiKeyHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var uri = request.RequestUri?.ToString();
request.Headers.Add("key", "value");
return base.SendAsync(request, cancellationToken);
}
}Register the Handler
The next step is to register the handler in the program.cs class. The AddDelegatingHandler also takes default global parameter that is set to false. If it is true, the handler is applied globally and if it is false, it is added to a specific route.
builder.Services.AddOcelot(builder.Configuration)
.AddDelegatingHandler<ApiKeyHandler>(); //the handler gets registeredAfter registering the handler, it should be configured in the ocelot.json file.
{
"GlobalConfiguration": {
"BaseUrl": "http://localhost:5001"
},
"Routes": [
{
"UpstreamPathTemplate": "/api/soccer/fixtures{params}",
"UpstreamHttpMethod": [
"POST"
],
"DownstreamPathTemplate": "/api/soccer/fixtures{params}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": "5002"
}
],
"AuthenticationOptions": {
"AuthenticationProviderKey": "Bearer"
},
"DelegatingHandlers": [
"ApiKeyHandler"
]
}
]
}Conclusion
I hope you found this article helpful! To dive deeper, be sure to explore the official Ocelot documentation for more advanced features and best practices. And if you’re looking for a structured learning path, don’t miss out on my full course on Udemy — designed to take your skills to the next level!










