AuthorizationForOcelot allows you to implement a custom authorizer service with Ocelot configuration file style.
This package is inspired and designed to use with SwaggerForOcelot, so for example you can use splitted into folder ocelot files.
- Configure Ocelot Gateway.
Follow the Ocelot documentation. Optionally, configure SwaggerForOcelot
- Install Nuget package into yout ASP.NET Core Ocelot project.
dotnet add package AuthorizationForOcelot
- Configure allowed scopes for authorizing AuthorizationForOcelot in
ocelot.json
.
{
"Routes": [
{
"DownstreamPathTemplate": "/{everything}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}
],
"UpstreamPathTemplate": "/customers/{everything}",
"UpstreamHttpMethod": [ "Post" ],
"UserRoles": [ "admin", "uploader" ]
},
{
"DownstreamPathTemplate": "/{everything}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}
],
"UpstreamPathTemplate": "/customers/{everything}",
"UpstreamHttpMethod": [ "Get" ],
"UserRoles": [ "user" ]
},
{
"DownstreamPathTemplate": "/{everything}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5002
}
],
"UpstreamPathTemplate": "/products/{everything}",
"UpstreamHttpMethod": [ "Get", "Post" ],
"UserRoles": [ "admin" ]
}
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:5000"
}
}
UserRoles
is the access level required for using the resource matching by Method, URI template, hosts and ports.
- Create your custom authorize service implementing
AuthorizationForOcelot.Abstractions.IAuthorizerForOcelot
public class MyCustomAuthorizerService : IAuthorizerForOcelot
{
public IEnumerable<string> FetchUserRoles(HttpRequest httpRequest)
{
// httpRequest object has the access token passed to Ocelot gateway, you can get the Bearer token here for example.
// Your logic must return an enumerable string of roles that user has access. Example:
return new List<string>()
{
"operator",
"accountant"
};
}
}
- In the
ConfigureServices
method ofStartup.cs
, register the AuthorizationForOcelot with your custom implemented authorizer.
services.AddAuthorizationWithOcelot<MyCustomAuthorizerService>(Configuration);
services.AddOcelot().AddAuthorizationOcelotHandler();
- In
ConfigureWebHostDefaults
method ofProgram.cs
, insert theAuthorizationForOcelot
configuration.
webBuilder.UseKestrel()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("ocelot.json", optional: false, reloadOnChange: false);
config.AddOcelotWithAuthorization(hostingContext.HostingEnvironment);
})
.UseStartup<Startup>();
You can use options to define custom ocelot filename or folder. See
demo
folder of this repository to more examples.