Styra.Opa 1.5.4

dotnet add package Styra.Opa --version 1.5.4
                    
NuGet\Install-Package Styra.Opa -Version 1.5.4
                    
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="Styra.Opa" Version="1.5.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Styra.Opa" Version="1.5.4" />
                    
Directory.Packages.props
<PackageReference Include="Styra.Opa" />
                    
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 Styra.Opa --version 1.5.4
                    
#r "nuget: Styra.Opa, 1.5.4"
                    
#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.
#addin nuget:?package=Styra.Opa&version=1.5.4
                    
Install Styra.Opa as a Cake Addin
#tool nuget:?package=Styra.Opa&version=1.5.4
                    
Install Styra.Opa as a Cake Tool

OPA C# SDK

License NuGet Version

[!IMPORTANT] The documentation for this SDK lives at https://docs.styra.com/sdk, with reference documentation available at https://styrainc.github.io/opa-csharp

You can use the Styra OPA SDK to connect to Open Policy Agent and Enterprise OPA deployments.

SDK Installation

Nuget

dotnet add package Styra.Opa

SDK Example Usage (high-level)

All the code examples that follow assume that the high-level SDK module has been imported, and that an OpaClient instance was created:

using Styra.Opa;


private string serverURL = "http://opa-host:8181";
private string path = "authz/allow";
private OpaClient opa;

opa = new OPAClient(serverURL);

var input = new Dictionary<string, object>() {
    { "user", "alice" },
    { "action", "read" },
    {"resource", "/finance/reports/fy2038_budget.csv"},
};

// (local variable) bool allowed
var allowed = await opa.check("authz/allow", input);
// (local variable) violations List<string>?
var violations = await opa.evaluate<List<string>>("authz/violations", input);

// Normal true/false cases...
if (allowed) {
    // ...
} else {
    Console.WriteLine("Violations: " + violations);
}

Input types

The check and evaluate methods are overloaded for most standard JSON types, which include the following variants for the input parameter:

C# type JSON equivalent type
bool Boolean
double Number
string String
List<object> Array
Dictionary<string, object> Object

Result Types

OpaClient.check

For the check method, the output type is always bool.

OpaClient.evaluate<T>

For the evaluate method, the output type is configurable using generics, as shown in the example below.

string path = "authz/accounts/max_limit";

double maxLimit
try {
    maxLimit = opa.evaluate<double?>(path, "example");
}
catch (OpaException) {
    maxLimit = 0.0f;
}

Nullable types are also allowed for output types, and if an error occurs during evaluation, a null result will be returned to the caller.

string path = "authz/accounts/max_limit";

double? maxLimit = opa.evaluate<double?>(path, "example");

If the selected return type <T> is possible to deserialize from the returned JSON, evaluate<T> will attempt to populate the variable with the value(s) present.

public struct AuthzStatus
{
    public AuthzStatus(bool allowed)
    {
        Allowed = allowed;
    }

    public double Allowed { get; }

    public override string ToString() => $"Application authorized: {Allowed}";
}

var input = new Dictionary<string, object>() {
    { "user", "alice" },
    { "action", "read" },
};

AuthzStatus status;
try {
    status = opa.evaluate<AuthzStatus>(path, input);
}
catch (OpaException) {
    status = new AuthzStatus(false);
}

[!NOTE] For low-level SDK usage, see the sections below.


OPA OpenAPI SDK (low-level)

Summary

For more information about the API: Enterprise OPA documentation

Table of Contents

SDK Example Usage

Example 1

using Styra.Opa.OpenApi;
using Styra.Opa.OpenApi.Models.Components;

var sdk = new OpaApiClient();

var res = await sdk.ExecuteDefaultPolicyWithInputAsync(
    input: Input.CreateNumber(
        4963.69D
    ),
    pretty: false,
    acceptEncoding: GzipAcceptEncoding.Gzip
);

// handle response

Example 2

using Styra.Opa.OpenApi;
using Styra.Opa.OpenApi.Models.Requests;

var sdk = new OpaApiClient();

ExecutePolicyWithInputRequest req = new ExecutePolicyWithInputRequest() {
    Path = "app/rbac",
    RequestBody = new ExecutePolicyWithInputRequestBody() {
        Input = Input.CreateBoolean(
            false
        ),
    },
};

var res = await sdk.ExecutePolicyWithInputAsync(req);

// handle response

Example 3

using Styra.Opa.OpenApi;
using Styra.Opa.OpenApi.Models.Components;
using Styra.Opa.OpenApi.Models.Requests;
using System.Collections.Generic;

var sdk = new OpaApiClient();

ExecuteBatchPolicyWithInputRequest req = new ExecuteBatchPolicyWithInputRequest() {
    Path = "app/rbac",
    RequestBody = new ExecuteBatchPolicyWithInputRequestBody() {
        Inputs = new Dictionary<string, Input>() {
            { "key", Input.CreateStr(
                "<value>"
            ) },
        },
    },
};

var res = await sdk.ExecuteBatchPolicyWithInputAsync(req);

// handle response

Available Resources and Operations

<details open> <summary>Available methods</summary>

OpaApiClient SDK

</details>

Server Selection

Override Server URL Per-Client

The default server can be overridden globally by passing a URL to the serverUrl: string optional parameter when initializing the SDK client instance. For example:

using Styra.Opa.OpenApi;
using Styra.Opa.OpenApi.Models.Components;

var sdk = new OpaApiClient(serverUrl: "http://localhost:8181");

var res = await sdk.ExecuteDefaultPolicyWithInputAsync(
    input: Input.CreateNumber(
        4963.69D
    ),
    pretty: false,
    acceptEncoding: GzipAcceptEncoding.Gzip
);

// handle response

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or throw an exception.

By default, an API error will raise a Styra.Opa.OpenApi.Models.Errors.SDKException exception, which has the following properties:

Property Type Description
Message string The error message
StatusCode int The HTTP status code
RawResponse HttpResponseMessage The raw HTTP response
Body string The response content

When custom error responses are specified for an operation, the SDK may also throw their associated exceptions. You can refer to respective Errors tables in SDK docs for more details on possible exception types for each operation. For example, the ExecuteDefaultPolicyWithInputAsync method throws the following exceptions:

Error Type Status Code Content Type
Styra.Opa.OpenApi.Models.Errors.ClientError 400, 404 application/json
Styra.Opa.OpenApi.Models.Errors.ServerError 500 application/json
Styra.Opa.OpenApi.Models.Errors.SDKException 4XX, 5XX */*

Example

using Styra.Opa.OpenApi;
using Styra.Opa.OpenApi.Models.Components;
using Styra.Opa.OpenApi.Models.Errors;

var sdk = new OpaApiClient();

try
{
    var res = await sdk.ExecuteDefaultPolicyWithInputAsync(
        input: Input.CreateNumber(
            4963.69D
        ),
        pretty: false,
        acceptEncoding: GzipAcceptEncoding.Gzip
    );

    // handle response
}
catch (Exception ex)
{
    if (ex is ClientError)
    {
        // Handle exception data
        throw;
    }
    else if (ex is Models.Errors.ServerError)
    {
        // Handle exception data
        throw;
    }
    else if (ex is Styra.Opa.OpenApi.Models.Errors.SDKException)
    {
        // Handle default exception
        throw;
    }
}

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme
BearerAuth http HTTP Bearer

To authenticate with the API the BearerAuth parameter must be set when initializing the SDK client instance. For example:

using Styra.Opa.OpenApi;
using Styra.Opa.OpenApi.Models.Components;

var sdk = new OpaApiClient(bearerAuth: "<YOUR_BEARER_TOKEN_HERE>");

var res = await sdk.ExecuteDefaultPolicyWithInputAsync(
    input: Input.CreateNumber(
        4963.69D
    ),
    pretty: false,
    acceptEncoding: GzipAcceptEncoding.Gzip
);

// handle response

Community

For questions, discussions and announcements related to Styra products, services and open source projects, please join the Styra community on Slack!

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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Styra.Opa:

Package Downloads
Styra.Opa.AspNetCore

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.5.4 176 4/24/2025
1.5.3 323 4/15/2025
1.5.2 163 4/11/2025
1.5.1 198 4/4/2025
1.5.0 1,350 2/19/2025
1.4.1 1,585 11/18/2024
1.3.7 2,236 9/16/2024
1.3.6 144 9/5/2024
1.3.5 126 9/4/2024
1.3.3 427 8/20/2024
1.3.0 159 8/19/2024
1.2.0 96 8/5/2024
1.1.1 380 6/27/2024
1.1.0 219 6/24/2024
1.0.2 147 6/21/2024
1.0.1 140 6/20/2024
1.0.0 273 6/4/2024
0.8.1 242 5/24/2024
0.8.0 169 5/17/2024
0.7.7 167 5/8/2024
0.7.5 108 5/2/2024
0.7.3 184 4/30/2024
0.1.0 97 12/11/2024