Table of Contents

Class OpaAuthorizationMiddleware

Namespace
Styra.Opa.AspNetCore
Assembly
Styra.Opa.AspNetCore.dll

We do not subclass from Microsoft's AuthorizationMiddleware because we are intentionally operating outside of the policy-based authorization system they provide.

public class OpaAuthorizationMiddleware
Inheritance
OpaAuthorizationMiddleware
Inherited Members

Constructors

OpaAuthorizationMiddleware(RequestDelegate, ILogger<OpaAuthorizationMiddleware>?, OpaClient?, string?, IContextDataProvider?)

This middleware class is designed to hook into the ASP.NET Core request processing pipeline, and allows OPA decisions to drive request authorization decisions.

If a request is rejected, this middleware class will write an Access Denied response, and will abort further request processing.

public OpaAuthorizationMiddleware(RequestDelegate next, ILogger<OpaAuthorizationMiddleware>? logger = null, OpaClient? opa = null, string? opaPath = null, IContextDataProvider? dataProvider = null)

Parameters

next RequestDelegate

RequestDelegate from ASP.NET Core.

logger ILogger<OpaAuthorizationMiddleware>

Optional logger for the middleware to use.

opa OpaClient

Optional OpaClient to use for request authorization.

opaPath string

Optional rule path for the OpaClient to query against.

dataProvider IContextDataProvider

Optional data provider. Injects additional context into the OPA query under input.context.data

Fields

ReasonKey

The "preferred" key where the access decision reason should be searched for in the OpaResponse object. A default value of 'en' is used. If the selected key is not present in the response, the lexicographically first key is used instead from the sorted key list.

public string ReasonKey

Field Value

string

Methods

InvokeAsync(HttpContext)

InvokeAsync hooks into the middleware pipeline for a request, and either rejects the request with an Access Denied response, or allows it through to other middleware or the main application to process further.

public Task InvokeAsync(HttpContext context)

Parameters

context HttpContext

HttpContext for the incoming request.

Returns

Task

MakeRequestInput(HttpContext)

public Dictionary<string, object> MakeRequestInput(HttpContext context)

Parameters

context HttpContext

Returns

Dictionary<string, object>

OpaRequest(HttpContext)

This method abstracts over the OPA evaluation, and automatically selects the default rule, or a rule based on the provided path.

You should consider using the OPA C# SDK (which the OPA ASP.NET Core SDK depends on) directly rather than using this method, as it should not be needed during normal use.

public Task<OpaResponse?> OpaRequest(HttpContext context)

Parameters

context HttpContext

The HttpContext to use for building the OPA authorization request.

Returns

Task<OpaResponse>

OpaResponse on success; null otherwise.