OPA
The opa
plugin supports the integration with Open Policy Agent (OPA), a unified policy engine and framework that helps defining and enforcing authorization policies. Authorization logics are defined in Rego and stored in OPA.
Once configured, the OPA engine will evaluate the client request to a protected route to determine whether the request should have access to the upstream resource based on the defined policies.
Examples
The examples below demonstrate how you can work with the opa
plugin for different scenarios.
Before proceeding, you should have a running OPA server, or start a new one in Docker:
docker run -d -p 8181:8181 --name opa openpolicyagent/opa run -s --log-level debug
run -s
starts OPA as a server.--log-level debug
prints debug information to examine the data APISIX pushes to OPA.
Implement a Basic Policy
The following example implements a basic authorization policy in OPA to allow only GET requests.
Create an OPA policy that only allows HTTP GET requests:
curl "http://127.0.0.1:8181/v1/policies/getonly" -X PUT \
-H "Content-Type: text/plain" \
-d '
package getonly
import input.request
default allow = false
allow {
request.method == "GET"
}'
Create a route with the opa
plugin as such:
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"id": "opa-route",
"uri": "/anything",
"plugins": {
"opa": {
"host": "http://192.168.2.104:8181",
"policy": "getonly"
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}'
❶ Configure the OPA server address. Replace with your IP address.