OpenPolicyAgent.Opa.Authorization 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package OpenPolicyAgent.Opa.Authorization --version 1.0.0
                    
NuGet\Install-Package OpenPolicyAgent.Opa.Authorization -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="OpenPolicyAgent.Opa.Authorization" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="OpenPolicyAgent.Opa.Authorization" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="OpenPolicyAgent.Opa.Authorization" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add OpenPolicyAgent.Opa.Authorization --version 1.0.0
                    
#r "nuget: OpenPolicyAgent.Opa.Authorization, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package OpenPolicyAgent.Opa.Authorization@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=OpenPolicyAgent.Opa.Authorization&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=OpenPolicyAgent.Opa.Authorization&version=1.0.0
                    
Install as a Cake Tool

OpenPolicyAgent.Opa.Authorization

A .NET NuGet package that provides attribute-based authorization for ASP.NET Core using Open Policy Agent (OPA).

Features

  • Attribute-based authorization: Use [OpaAuthorize] attribute on controllers and methods
  • Seamless ASP.NET Core integration: Works with existing authentication and authorization infrastructure
  • Policy-based decisions: Delegate authorization logic to OPA policies
  • Flexible configuration: Configure OPA URL, policy paths, and custom context data
  • Compatible with OPA ecosystem: Built on top of the official OpenPolicyAgent.Opa package

Installation

Install the package via NuGet:

dotnet add package OpenPolicyAgent.Opa.Authorization

Quick Start

1. Configure OPA Authorization

In your Program.cs or Startup.cs:

using OpenPolicyAgent.Opa.Authorization;

var builder = WebApplication.CreateBuilder(args);

// Add authentication (required)
builder.Services.AddAuthentication(/* your authentication configuration */);

// Add OPA authorization
builder.Services.AddOpaAuthorization(options =>
{
    options.OpaUrl = "http://localhost:8181";
    options.DefaultPolicyPath = "authz/allow";
});

builder.Services.AddControllers();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

2. Use the OpaAuthorize Attribute

Apply the [OpaAuthorize] attribute to your controllers or actions:

using Microsoft.AspNetCore.Mvc;
using OpenPolicyAgent.Opa.Authorization;

[ApiController]
[Route("api/[controller]")]
public class DocumentsController : ControllerBase
{
    // Uses the default policy path configured in options
    [OpaAuthorize]
    [HttpGet]
    public IActionResult GetAll()
    {
        return Ok(new[] { "document1", "document2" });
    }

    // Uses a custom policy path for this specific action
    [OpaAuthorize("authz/documents/allow")]
    [HttpGet("{id}")]
    public IActionResult GetById(int id)
    {
        return Ok($"document{id}");
    }

    // Includes extra information (available as input.context.metadata in OPA)
    [OpaAuthorize("authz/documents/allow", "AdminOperation")]
    [HttpPost]
    public IActionResult Create([FromBody] object document)
    {
        return Created("", document);
    }
}

3. Create OPA Policy

Create a Rego policy file (e.g., policy.rego):

package authz

# Default deny
default allow = false

# Allow GET requests to /api/documents for authenticated users
allow {
    input.action.name == "GET"
    startswith(input.resource.id, "/api/documents")
    input.subject.id != ""
}

# Allow POST requests only for admin users
allow {
    input.action.name == "POST"
    startswith(input.resource.id, "/api/documents")
    some claim in input.subject.claims
    claim.type == "role"
    claim.value == "admin"
}

4. Run OPA Server

Start an OPA server with your policy:

opa run --server --addr localhost:8181 policy.rego

Configuration Options

OpaAuthorizationOptions

builder.Services.AddOpaAuthorization(options =>
{
    // OPA server URL (default: http://localhost:8181)
    options.OpaUrl = "http://localhost:8181";

    // Default policy path to evaluate (optional)
    options.DefaultPolicyPath = "authz/allow";

    // Preferred language key for access denial reasons (default: "en")
    options.ReasonKey = "en";

    // Allow unauthenticated requests (default: false)
    options.AllowUnauthenticated = false;
});

Environment Variable Configuration

You can also configure the OPA URL via environment variable:

export OPA_URL=http://opa-server:8181

Custom Context Data Provider

Inject additional context data into OPA evaluation:

public class CustomContextDataProvider : IOpaContextDataProvider
{
    public object GetContextData(HttpContext context)
    {
        return new
        {
            tenant_id = context.Request.Headers["X-Tenant-Id"].ToString(),
            request_time = DateTime.UtcNow
        };
    }
}

// Register the provider
builder.Services.AddOpaContextDataProvider<CustomContextDataProvider>();

This data will be available under input.context.data in your OPA policy.

OPA Input Schema

The package sends the following input to OPA:

{
  "subject": {
    "type": "aspnetcore_authentication",
    "id": "<user identity name>",
    "claims": [/* array of user claims */]
  },
  "resource": {
    "type": "endpoint",
    "id": "<request path>"
  },
  "action": {
    "name": "<HTTP method>",
    "protocol": "<HTTP protocol>",
    "headers": {/* request headers */}
  },
  "context": {
    "type": "http",
    "host": "<request host>",
    "ip": "<remote IP address>",
    "port": <remote port>,
    "data": {/* custom context data, if provider registered */},
    "metadata": "<extra information from attribute, if provided>"
  }
}

Note: The metadata field is only included when using [OpaAuthorize("policy/path", "Extra Information")] with the second parameter.

OPA Response Schema

The package expects the following response from OPA:

{
  "allow": true,
  "reason": "Access granted" // or {"en": "Access granted", "es": "Acceso concedido"}
}

Examples

See the samples directory for complete working examples.

Dependencies

This package is built on top of:

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 53 11/4/2025
1.0.2 64 11/3/2025
1.0.1 66 11/3/2025
1.0.0 149 10/29/2025