opa
The type
indicates that the request type. (e.g. http
or stream
) The reqesut
is used when the request type is http
, it contains the basic information of the request. (e.g. url, header) The var
contains basic information about this requested connection. (e.g. IP, port, request timestamp) The route
, service
, and consumer
will be sent only after the opa
plugin has enabled the relevant features, and their contents are same as those stored by APISIX in etcd.
In the response, result
is automatically added by OPA. The allow
is indispensable and will indicate whether the request is allowed to be forwarded through the APISIX. The reason
, headers
, and status_code
are optional and are only returned when you need to use a custom response, as you’ll see in the next section with the actual use case for it.
{
"result": {
"allow": true,
"reason": "test",
"headers": {
"an": "header"
},
"status_code": 401
}
}
First, you need to launch the Open Policy Agent environment.
$ docker run -d --name opa -p 8181:8181 openpolicyagent/opa:0.35.0 run -s
After that, you can create a route and turn on the opa
plugin.
-H 'X-API-KEY: <api-key>' \
-H 'Content-Type: application/json' \
-d '{
"uri": "/*",
"opa": {
"host": "http://127.0.0.1:8181",
"policy": "example1"
}
},
"upstream": {
"nodes": {
"httpbin.org:80": 1
},
"type": "roundrobin"
}
}'
Try it out.
# Successful request
$ curl -i -X GET 127.0.0.1:9080/get
HTTP/1.1 200 OK
# Failed request
$ curl -i -X POST 127.0.0.1:9080/post
HTTP/1.1 403 FORBIDDEN
Next, let’s think about some more complex scenarios.
Update the route and set opa
plugin’s policy
parameter to example2
. Then, let’s try it.
# Successful request
$ curl -i -X GET 127.0.0.1:9080/get
$ curl -i -X POST 127.0.0.1:9080/post
HTTP/1.1 302 FOUND
Location: http://example.com/auth
test
Let’s think about another scenario, when your decision needs to use some APISIX data, such as route
, consumer
, etc., how should we do it?
Create a simple policy echo
, which will return the data sent by APISIX to the OPA service as is, so we can simply see them.
$ curl -X PUT '127.0.0.1:8181/v1/policies/echo' \
-H 'Content-Type: text/plain' \
-d 'package echo
allow = false
reason = input'
Try it. As you can see, we output this data with the help of the custom response body function described above, along with the data from the route.
$ curl -X GET 127.0.0.1:9080/get
{
"type": "http",
"request": {
xxx
},
"var": {
xxx
},
"route": {
xxx