APISIX Consumer用法 - consumer-res
2023-01-13 本文已影响0人
heichong
本篇文章讲述如果通过
consumer-restriction
来限制路由的访问权限(黑白名单机制)
原始情况
我有一个消费者配置如下:
{
"username": "helloConsumer",
"desc": "hello消费者",
"plugins": {
"key-auth": {
"disable": false,
"key": "1234567890"
}
}
}
我有两个路由:
- 路由test1
{
"uri": "/test1/**",
"name": "test1",
"methods": [
"GET",
"POST",
"PUT",
"DELETE",
"PATCH",
"HEAD",
"OPTIONS",
"CONNECT",
"TRACE",
"PURGE"
],
"plugins": {
"key-auth": {
"disable": false,
"header": "token"
},
"proxy-rewrite": {
"regex_uri": [
"^/test1/(.*)",
"/$1"
]
}
},
"upstream_id": "442135180308644824",
"status": 1
}
- 路由test2
{
"uri": "/test2/*",
"name": "test2",
"methods": [
"GET",
"POST",
"PUT",
"DELETE",
"PATCH",
"HEAD",
"OPTIONS",
"CONNECT",
"TRACE",
"PURGE"
],
"plugins": {
"key-auth": {
"disable": false,
"header": "token"
},
"proxy-rewrite": {
"regex_uri": [
"^/test2/(.*)",
"/$1"
]
}
},
"upstream_id": "442135180308644824",
"status": 1
}
正常情况下,通过以下方式,两个路由都可以访问
[root@KSSYSDEV ~]# curl http://10.3.23.191:9906/test1/hello -H 'token:1234567890'
Hello World, From Port 9999
[root@KSSYSDEV ~]# curl http://10.3.23.191:9906/test2/hello -H 'token:1234567890'
Hello World, From Port 9998
目的
如果我想/test1可以被helloConsumer访问,而/test2不能被helloConsumer访问,改如何处理?
这里就需要使用consumer-restriction,它可以给路由配置黑白名单
调整配置
重新修改路由如下:
- 修改路由1
{
"uri": "/test1/**",
"name": "test1",
"methods": [
"GET",
"POST",
"PUT",
"DELETE",
"PATCH",
"HEAD",
"OPTIONS",
"CONNECT",
"TRACE",
"PURGE"
],
"plugins": {
"consumer-restriction": {
"disable": false,
"whitelist": [
"helloConsumer"
]
},
"key-auth": {
"disable": false,
"header": "token"
},
"proxy-rewrite": {
"regex_uri": [
"^/test1/(.*)",
"/$1"
]
}
},
"upstream_id": "442135180308644824",
"status": 1
}
- 修改路由2
{
"uri": "/test2/*",
"name": "test2",
"methods": [
"GET",
"POST",
"PUT",
"DELETE",
"PATCH",
"HEAD",
"OPTIONS",
"CONNECT",
"TRACE",
"PURGE"
],
"plugins": {
"consumer-restriction": {
"disable": false,
"rejected_code": 403,
"rejected_msg": "您没有权限访问此服务!",
"whitelist": [
"helloConsumer2"
]
},
"key-auth": {
"disable": false,
"header": "token"
},
"proxy-rewrite": {
"regex_uri": [
"^/test2/(.*)",
"/$1"
]
}
},
"upstream_id": "442135180308644824",
"status": 1
}
这里
helloConsumer2
是我随便配的,可以改成自己的consumerName。
- 我们再次尝试访问/test1和/test2
[root@KSSYSDEV ~]#
[root@KSSYSDEV ~]# curl http://10.3.23.191:9906/test1/hello -H 'token:1234567890'
Hello World, From Port 9999[root@KSSYSDEV ~]#
[root@KSSYSDEV ~]#
[root@KSSYSDEV ~]# curl http://10.3.23.191:9906/test2/hello -H 'token:1234567890'
{"message":"您没有权限访问此服务!"}
可以看到,此consumer只能访问/test1,而无法访问/test2