Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrate Open Policy Agent with ASP.Net Core web API

I was going through some videos and tutorials on OPA (Open Policy Agent) and found it really cool to use it for implementing Authentication and Authorization across multiple services / APIs. However I am not able to get any insights on how to install it on windows and integrate it with an ASP.Net core Web API to implement Authentication and Authorization. Can anyone help me in this ?

Thanks,

Amit Anand

like image 431
Amit Anand Avatar asked Jan 26 '23 09:01

Amit Anand


2 Answers

Without knowing more about your use case or the platform you're running on, here's some general advice.

  1. Architecture. Decide whether you want to run OPA as a sidecar or as a standalone service. That's an architectural question that will depend on latency, performance, and the data you need for your policies. OPA is a building-block designed as a sidecar, but you can build a service around OPA by spinning up multiple copies, load-balancing across them, adding a persistence layer, etc.

  2. Administration. Decide how to load/update policies and log decisions to OPA and if applicable, decide how to load data into OPA.

  3. Service Integration. If you are using a network proxy that intercepts all network traffic going to your services (e.g. Envoy, Linkerd, Kong, ...) you can configure your network proxy to call out to OPA without modifying your .Net service. If you're not using a network proxy, modify your .Net services to make HTTP callouts when your services need policy decisions, using a library where possible to minimize the impact on individual services. The integration page shows how for Java Spring and PHP.

like image 165
Tim Hinrichs Avatar answered Jan 27 '23 22:01

Tim Hinrichs


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.

like image 21
Colin McCullough Avatar answered Jan 27 '23 23:01

Colin McCullough