Tim Hinrichs' answer above is on point. However, to add to it here are some specific solutions. Out of the 2 solutions below, I would recommend using the REST API and ASP.NET middleware. Also, while OPA can theoretically be used as an Authentication tool, I would advise against it. It's purpose is Authorization.
Use ASP.NET Authorization Middleware
Firstly, OPA would be running either as it's own service, as a sidecar in k8's, or in a Docker container. OPA's documentation does a good job showing examples on how to implement that so I won't go into specifics.
Here you would create a .NET service that queries OPA's Rest API.
- Here is a a complete example here
- Here is Microsoft's documentation on using middleware
This is what the middleware would look like.
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace Authz.Opa
{
public class OpaAuthzMiddleware
{
private const string ForbiddenMessage = "Forbidden";
private readonly RequestDelegate _next;
private readonly IOpaService _opaService;
public OpaAuthzMiddleware(RequestDelegate next, IOpaService service)
{
_next = next;
_opaService= service;
}
public async Task InvokeAsync(HttpContext context)
{
var enforceResult = await _opaService.RunAuthorizationAsync(context);
if (!enforceResult)
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.WriteAsync(ForbiddenMessage);
return;
}
await _next(context);
}
}
}
and you would implement it in your startup like this
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Sample
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddRouting();
services.AddSingleton<IOpaService, OpaService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseMiddleware<OpaAuthzMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Use OPA's Wasm compilation
OPA has tooling that can compile Rego policies into executable Wasm modules. They provide documentation here.
It's currently under development, but there is an example on using this in .NET here. Looking at the discussions under that repo's Issues section, it looks like they're still working out some things.
You would need to use one of the available .NET libraries to read the compiled Wasm files, but this is considered to be the fastest evaluation method that OPA offers.