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.

    1. type Input struct {
    2. request HTTPRequest
    3. }
    4. type HTTPRequest struct {
    5. // The request method (e.g. GET,POST,etc...)
    6. method string
    7. // The raw request path (e.g. "/v2/my-path/")
    8. path string
    9. path_parts string[]
    10. // The raw query string (e.g. "?a=1&b=2")
    11. raw_query string
    12. // The query broken down into keys and their values
    13. query map[string][]string
    14. // The request headers
    15. // NOTE: By default, no headers are included. You must specify what headers
    16. // you want to recieve via `spec.metadata.includedHeaders` (see above)
    17. // The request scheme (e.g. http, https)
    18. scheme string
    19. }

    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:

    1. package http
    2. default allow = {
    3. "allow": false
    4. }

    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:

    1. package http
    2. default allow = {
    3. "allow": false,
    4. "status_code": 301,
    5. "additional_headers": {
    6. "Location": "https://my.redirect.site"
    7. }
    8. }
    1. type Result bool
    2. // or
    3. type Result struct {
    4. // Whether to allow or deny the incoming request
    5. allow bool
    6. // Overrides denied response status code; Optional
    7. status_code int
    8. // Sets headers on allowed request or denied response; Optional
    9. additional_headers map[string]string
    10. }