How-To: Apply Open Policy Agent (OPA) policies
The Dapr Open Policy Agent (OPA) HTTP middleware allows applying to incoming Dapr HTTP requests. This can be used to apply reusable authorization policies to app endpoints.
You can prototype and experiment with policies using the official opa playground. For example, .
The HTTPRequest
input contains all the revelant information about an incoming HTTP Request except it’s body.
type Input struct {
request HTTPRequest
}
type HTTPRequest struct {
// The request method (e.g. GET,POST,etc...)
method string
// The raw request path (e.g. "/v2/my-path/")
path string
path_parts string[]
// The raw query string (e.g. "?a=1&b=2")
raw_query string
// The query broken down into keys and their values
query map[string][]string
// The request headers
// NOTE: By default, no headers are included. You must specify what headers
// you want to recieve via `spec.metadata.includedHeaders` (see above)
// The request scheme (e.g. http, https)
scheme string
}
The policy must set data.http.allow
with either a boolean
value, or an object
value with an allow
boolean property. A true
allow
will allow the request, while a false
value will reject the request with the status specified by defaultStatus
. The following policy, with defaults, demonstrates a 403 - Forbidden
for all requests:
package http
default allow = {
"allow": false
}
When rejecting a request, you can override the status code the that gets returned. For example, if you wanted to return a 401
instead of a 403
, you could do the following:
To redirect, add headers and set the to the returned result:
package http
default allow = {
"allow": false,
"status_code": 301,
"additional_headers": {
"Location": "https://my.redirect.site"
}
}
type Result bool
// or
type Result struct {
// Whether to allow or deny the incoming request
allow bool
// Overrides denied response status code; Optional
status_code int
// Sets headers on allowed request or denied response; Optional
additional_headers map[string]string
}