如何使用API网关和OPA实现RBAC

目前,为了确保合适的人员能够访问到合适的资源,我们需要对系统启用适当的访问控制方式。不过,面对各种广为熟悉的实现模型,构建其后端服务的API授权体系,往往是一个不小的挑战。在本文中,我们将讨论如何使用开源的API网关–Apache APISIX(apisix.apache.org/)和开放策略代理(Open Policy Agent,OPA,www.openpolicyagent.org/docs/latest…)为自己的API启用基于角色的访问控制(Role-based access control,RBAC)授权模型。

一、什么是RBAC?

基于角色的访问控制(RBAC,en.wikipedia.org/wiki/Role-b… 和基于属性的访问控制(attribute-based access control,ABAC,en.wikipedia.org/wiki/Attrib… 是两种最常用的访问控制模型,可用于管理计算机系统中的权限和对资源的访问。通常,RBAC会根据用户在组织中的角色职能与职责,向其分配权限。

也就是说,在RBAC中,角色是根据用户的功能或职责定义的,并为这些角色分配相应的权限。当然,在实际运营中,我们时常会给用户分配一到多个角色,以便他们继承与这些角色相关联的权限。例如,在API的上下文中,开发人员角色可能有权创建和更新API资源,而最终用户角色只有读取或执行API资源的权限。而且,在RBAC中,策略是由用户所分配的角色、他们有权执行的操作、以及他们执行操作时所需的资源等组合因素来定义的。如果说RBAC是根据用户角色来分配权限的话,那么ABAC则是根据与用户和资源所关联的属性来分配权限的。

二、什么是OPA?

作为一个策略引擎和一组工具,OPA提供了一种统一的方法,来横跨整个分布式系统去执行策略。它允许开发者从一个端点集中定义、管理和实施策略。通过将策略定义为代码,OPA可以轻松地审查、编辑和回滚策略,从而促进高效的策略管理。

如上图所示,OPA提供了一种被称为Rego(www.openpolicyagent.org/docs/latest… 的声明性语言。它允许您在整个技术栈中创建和实施各种策略。当您向OPA请求某个政策决策时,它会使用您在文件中提供的规则和数据,来评估查询并生成响应,然后再将查询的结果作为策略决策,发回给您。由于OPA将其所需的所有策略和数据都存储在其内部缓存之中,因此它可以快速地返回结果。下面是一个简单的OPA Rego文件示例:

package example
default allow = false
allow {
input.method == "GET"
input.path =="/api/resource"
input.user.role == "admin"
}
package example

default allow = false
allow {
   
input.method == "GET"
   
input.path =="/api/resource"
    input.user.role == "admin"
}
package example default allow = false allow { input.method == "GET" input.path =="/api/resource" input.user.role == "admin" }

如上面的代码段所示,我们有一个名为“example”的包,它定义了一个名为“allow”的规则。该规则指定:如果输入方法是“GET”,请求的路径是/api/resource,并且用户角色是“admin”,则允许该请求。也就是说,如果同时满足这些条件,则“allow”规则将其评估为“真”,从而允许该请求继续进行。

三、为什么可针对RBAC使用OPA和API网关?

API网关提供了一个集中位置,来配置和管理API及其使用者。作为集中式身份验证网关,它有效地避免了让每个单独的服务,在其内部实现身份验证的逻辑。另一方面,OPA通过为授权创建一个单独的授权层,来将策略与代码分离。而通过这种组合,您可以将API资源的权限添加到角色上,进而为每个用户角色都定义一组对于RBAC资源(由URI路径来定义)的权限(GET、PUT、DELETE)。在下一节中,我们将学习如何使用两者来实现RBAC。

四、如何使用OPA和Apache APISIX实现RBAC

在Apache APISIX中,您可以通过配置路由(apisix.apache.org/docs/apisix… 和插件(apisix.apache.org/docs/apisix… ,来定义API的行为。具体而言,您可以使用APISIX的OPA插件(apisix.apache.org/docs/apisix… ,通过将请求转发给OPA进行决策,来执行RBAC的相关策略。也就是说,OPA会根据用户的角色和权限,实时做出授权决策。

假设我们有一个Conference API(conferenceapi.azurewebsites.net/) ,您可以在其中检索/编辑活动会话、主题、以及演讲者信息。在授权方面,演讲者只能阅读自己的会话和主题,而管理员则可以添加/编辑更多会话和主题。而且,与会者可以通过POST请求,向/speaker/speakerId/session/feedback路径留下他们针对演讲者会议的反馈,而演讲者只能通过请求相同URI的GET方法才能看到。下图展示了整个场景:

1.  API使用者会在API网关上使用其凭据(如:授权标头中的JWT令牌, developer.mozilla.org/en-US/docs/… 来请求路由。

2.  API网关将带有JWT标头的使用者数据发送到OPA引擎。

3.  OPA使用我们在.rego文件中指定的策略(如:角色和权限),来评估使用者是否有权访问资源。

4.  如果OPA决定为“允许”,则该请求将被转发到上游的Conference服务。

接着,我们来安装和配置APISIX,并在OPA中定义各项策略。

五、先决条件

第 1 步:安装Apache APISIX

APISIX可以使用以下脚本被轻松地安装和快速启动:

curl -sL https://run.api7.ai/apisix/quickstart | sh
curl -sL https://run.api7.ai/apisix/quickstart | sh
curl -sL https://run.api7.ai/apisix/quickstart | sh

第 2 步:配置后端服务(上游)

为了将请求路由到Conference API的后端服务,您需要通过Admin API(apisix.apache.org/docs/apisix… 在Apache APISIX中添加上游服务器来进行配置。请参见如下代码:

curl http://127.0.0.1:9180/apisix/admin/upstreams/1
-X PUT -d '
{
"name":"Conferences API upstream",
"desc":"Register Conferences API as the upstream",
"type":"roundrobin",
"scheme":"https",
"nodes":{
"conferenceapi.azurewebsites.net:443":1
}
}'
curl http://127.0.0.1:9180/apisix/admin/upstreams/1
-X PUT -d '


{





  


"name":"Conferences API upstream",
  
"desc":"Register Conferences API as the upstream",
  
"type":"roundrobin",
  
"scheme":"https",
  
"nodes":{
     
"conferenceapi.azurewebsites.net:443":1
   }
}'
curl http://127.0.0.1:9180/apisix/admin/upstreams/1 -X PUT -d ' { "name":"Conferences API upstream", "desc":"Register Conferences API as the upstream", "type":"roundrobin", "scheme":"https", "nodes":{ "conferenceapi.azurewebsites.net:443":1 } }'

第 3 步:创建API使用者

接下来,我们使用用户名Jack在Apache APISIX中创建一个使用者(即,一个新的发言人),并使用指定的密钥为使用者设置jwt-auth(apisix.apache.org/docs/apisix…)插件,以便使用者使用JSON Web Token(JWT,jwt.io/)进行身份验证。请参见如下代码:

curl http://127.0.0.1:9180/apisix/admin/consumers
-X PUT -d '
{
"username": "jack",
"plugins": {
"jwt-auth": {
"key": "user-key",
"secret": "my-secret-key"
}
}
}'
curl http://127.0.0.1:9180/apisix/admin/consumers
-X PUT -d '


{





   


"username": "jack",
   


"plugins": {

       
"jwt-auth": {
           
"key": "user-key",
           
"secret": "my-secret-key"
        }
    }
}'
curl http://127.0.0.1:9180/apisix/admin/consumers -X PUT -d ' { "username": "jack", "plugins": { "jwt-auth": { "key": "user-key", "secret": "my-secret-key" } } }'

第 4 步:创建公共端点以生成JWT令牌

您还需要设置一个使用public-api(apisix.apache.org/docs/apisix…)插件来生成和签发令牌的新路由。此时,API网关会充当身份提供者服务器(identity provider server)的角色,去验证由使用者Jack的密钥所创建和验证的令牌。当然,身份提供者也可以是诸如Google(developers.google.com/identity)、O…www.keycloak.org/)和Ory Hydra(www.ory.sh/hydra/)等任何第三方服务。请参见如下代码:

curl http://127.0.0.1:9180/apisix/admin/routes/jas
-X PUT -d '
{
"uri": "/apisix/plugin/jwt/sign",
"plugins": {
"public-api": {}
}
}'
curl http://127.0.0.1:9180/apisix/admin/routes/jas
-X PUT -d '


{





   


"uri": "/apisix/plugin/jwt/sign",
   


"plugins": {

        "public-api": {}
    }
}'
curl http://127.0.0.1:9180/apisix/admin/routes/jas -X PUT -d ' { "uri": "/apisix/plugin/jwt/sign", "plugins": { "public-api": {} } }'

第 5 步:为API使用者申请一个新的JWT令牌

现在,我们可以使用已创建的公共端点,从API网关处为Jack获取一个新的令牌了。如下curl命令便是使用Jack的凭据生成一个新令牌,并在负载中分配了角色和权限。

curl -G –data-urlencode ‘payload={“role”:”speaker”,”permission”:”read”}’ http://127.0.0.1:9080/apisix/plugin/jwt/sign?key=user-key -i

在运行了上述命令后,您将收到一个新的令牌作为响应。我们暂且将该令牌保存在某处,以便稍后使用它去访问新的API网关端点。

第 6 步:创建新的插件配置

此步骤会涉及到配置APISIX的3个插件,分布是:proxy-rewrite(apisix.apache.org/docs/apisix…apisix.apache.org/docs/apisix…)和OPA(apisix.apache.org/docs/apisix…)插件。请参见如下代码:

curl
"http://127.0.0.1:9180/apisix/admin/plugin_configs/1" -X PUT -d '
{
"plugins":{
"jwt-auth":{
},
"proxy-rewrite":{
"host":"conferenceapi.azurewebsites.net"
}
}
}'
curl


"http://127.0.0.1:9180/apisix/admin/plugin_configs/1" -X PUT -d '
{





  


"plugins":{

     

"jwt-auth":{
      },
     
"proxy-rewrite":{
        
"host":"conferenceapi.azurewebsites.net"
      }
   }
}'
curl "http://127.0.0.1:9180/apisix/admin/plugin_configs/1" -X PUT -d ' { "plugins":{ "jwt-auth":{ }, "proxy-rewrite":{ "host":"conferenceapi.azurewebsites.net" } } }'
  • proxy-rewrite插件被配置为将请求全部代理到conferenceapi.azurewebsites.net主机处。
  • OPA身份验证插件被配置为使用在http://localhost:8181/v1/data/rbacExample 上运行的OPA策略引擎。此外,APISIX将所有与使用者相关的信息,都发送给OPA。我们需要在OPA的配置部分里添加.rego文件。

第 7 步:为Conference会话创建路由

最后一步是为Conferences API的演讲者会话创建新的路由:

curl
"http://127.0.0.1:9180/apisix/admin/routes/1" -X PUT -d '
{
"name":"Conferences API speaker sessions route",
"desc":"Create a new route in APISIX for the Conferences
API speaker sessions",
"methods": ["GET", "POST"],
"uris":
["/speaker/*/topics","/speaker/*/sessions"],
"upstream_id":"1",
"plugin_config_id":1
}'
curl


"http://127.0.0.1:9180/apisix/admin/routes/1" -X PUT -d '
{





   


"name":"Conferences API speaker sessions route",
   


"desc":"Create a new route in APISIX for the Conferences
API speaker sessions",
   

"methods": ["GET", "POST"],
   

"uris":
["/speaker/*/topics","/speaker/*/sessions"],
   
"upstream_id":"1",
   
"plugin_config_id":1
}'
curl "http://127.0.0.1:9180/apisix/admin/routes/1" -X PUT -d ' { "name":"Conferences API speaker sessions route", "desc":"Create a new route in APISIX for the Conferences API speaker sessions", "methods": ["GET", "POST"], "uris": ["/speaker/*/topics","/speaker/*/sessions"], "upstream_id":"1", "plugin_config_id":1 }'

上述负载包含了诸如:名称、描述、方法、URI、上游ID和插件配置ID等路由信息。在本例中,路由被配置为处理两个不同URI(/speaker/topics和/speaker/sessions)的GET和POST请求。其中,“upstream_id”字段指定了将处理该路由传入请求的、上游服务的ID,而“plugin_config_id”字段则指定了将用于此路由的、插件配置的ID。

第 8 步:在没有OPA的情况下测试设置

到目前为止,我们已经为APISIX设置了所有必要的配置,以将传入的请求定向到Conference API的各个端点上,并且只允许那些已被授权的API使用者使用。据此,在每次API使用者需要访问端点时,他们都必须提供JWT令牌,以从Conference后端服务中检索到数据。您可以通过点击端点来对此进行验证。在此,我们所请求的域地址是自定义API网关,而不是实际的Conference服务:

curl -i http://127.0.0.1:9080/speaker/1/topics -H
'Authorization: {API_CONSUMER_TOKEN}'
curl -i http://127.0.0.1:9080/speaker/1/topics -H

'Authorization: {API_CONSUMER_TOKEN}'
curl -i http://127.0.0.1:9080/speaker/1/topics -H 'Authorization: {API_CONSUMER_TOKEN}'

第 9 步:运行OPA服务

接着,我们使用Docker来运行OPA服务,并使用其API来上传我们的策略定义。该API可用于评估各个传入请求的授权策略。

docker run -d --network=apisix-quickstart-net
--name opa -p 8181:8181 openpolicyagent/opa:latest run -s
docker run -d --network=apisix-quickstart-net
--name opa -p 8181:8181 openpolicyagent/opa:latest run -s
docker run -d --network=apisix-quickstart-net --name opa -p 8181:8181 openpolicyagent/opa:latest run -s

上述Docker命令启动了一个具有最新版本的OPA镜像容器。它在现有的APISIX网络apisix-quickstart-net上,创建了一个名为OPA,并公开了端口8181的新容器。因此,APISIX可以直接使用地址–http://opa:8181,向OPA发送策略检查请求。注意OPA和APISIX应该运行在同一个Docker网络中。

第 10 步:定义和注册策略

OPA端的下一步是需要定义将用于控制对API资源进行访问的策略。这些策略应定义访问所需的属性(如:哪些用户具有哪些角色)、以及基于这些属性允许或拒绝的权限(如:哪些角色具有哪些权限)。举例而言,在下面的配置中,我们要求OPA检查表user_roles,以找到角色Jack。这些信息是由APISIX内部的input.consumer.username发送的。我们据此通过读取JWT的有效载荷,并从中提取token.payload.permission,来验证使用者的权限。如下注释清楚地描述了这些步骤。

curl -X PUT
'127.0.0.1:8181/v1/policies/rbacExample' \
-H
'Content-Type: text/plain' \
-d
'package rbacExample
# Assigning user rolesuser_roles := {
"jack": ["speaker"],
"bobur":["admin"]
}
# Role permission assignments
role_permissions := {
"speaker": [{"permission": "read"}],
"admin":
[{"permission": "read"}, {"permission":
"write"}]
}
# Helper JWT Functions
bearer_token := t {
t :=
input.request.headers.authorization
}
# Decode the authorization token to get a role and
permission
token = {"payload": payload} {
[_, payload,
_] := io.jwt.decode(bearer_token)
}
# Logic that implements RBAC
default allow = falseallow {
# Lookup
the list of roles for the user
roles :=
user_roles[input.consumer.username] #
For each role in that list
r :=
roles[_] # Lookup the permissions list
for role r
permissions := role_permissions[r]
# For each permission
p :=
permissions[_] # Check if the
permission granted to r matches the users request
p ==
{"permission": token.payload.permission}
}'
curl -X PUT
'127.0.0.1:8181/v1/policies/rbacExample' \
    -H
'Content-Type: text/plain' \
    -d
'package rbacExample

# Assigning user rolesuser_roles := {
   

"jack": ["speaker"],
   

"bobur":["admin"]
}

# Role permission assignments
role_permissions := {
   
"speaker": [{"permission": "read"}],
   
"admin":  
[{"permission": "read"}, {"permission":
"write"}]
}

# Helper JWT Functions
bearer_token := t {
 t :=
input.request.headers.authorization
}

# Decode the authorization token to get a role and
permission
token = {"payload": payload} {
 [_, payload,
_] := io.jwt.decode(bearer_token)
}

# Logic that implements RBAC
default allow = falseallow {
    # Lookup
the list of roles for the user
    roles :=
user_roles[input.consumer.username]    #
For each role in that list
    r :=
roles[_]    # Lookup the permissions list
for role r
   
permissions := role_permissions[r]   
# For each permission
    p :=
permissions[_]    # Check if the
permission granted to r matches the users request
    p ==
{"permission": token.payload.permission}
}'
curl -X PUT '127.0.0.1:8181/v1/policies/rbacExample' \ -H 'Content-Type: text/plain' \ -d 'package rbacExample # Assigning user rolesuser_roles := { "jack": ["speaker"], "bobur":["admin"] } # Role permission assignments role_permissions := { "speaker": [{"permission": "read"}], "admin": [{"permission": "read"}, {"permission": "write"}] } # Helper JWT Functions bearer_token := t { t := input.request.headers.authorization } # Decode the authorization token to get a role and permission token = {"payload": payload} { [_, payload, _] := io.jwt.decode(bearer_token) } # Logic that implements RBAC default allow = falseallow { # Lookup the list of roles for the user roles := user_roles[input.consumer.username] # For each role in that list r := roles[_] # Lookup the permissions list for role r permissions := role_permissions[r] # For each permission p := permissions[_] # Check if the permission granted to r matches the users request p == {"permission": token.payload.permission} }'

步骤 11:使用OPA插件更新现有插件配置

一旦在OPA服务上定义了各项策略,我们就需要更新现有的插件配置,以便路由去使用OPA插件。如下代码段所示,我们需要在OPA插件的policy属性中来指定。

curl
"http://127.0.0.1:9180/apisix/admin/plugin_configs/1" -X PATCH -d '
{
"plugins":{
"opa":{
"host":"http://opa:8181",
"policy":"rbacExample",
"with_consumer":true
}
}
}'
curl


"http://127.0.0.1:9180/apisix/admin/plugin_configs/1" -X PATCH -d '
{





  


"plugins":{

     

"opa":{
        
"host":"http://opa:8181",
        
"policy":"rbacExample",
        
"with_consumer":true
      }
   }
}'
curl "http://127.0.0.1:9180/apisix/admin/plugin_configs/1" -X PATCH -d ' { "plugins":{ "opa":{ "host":"http://opa:8181", "policy":"rbacExample", "with_consumer":true } } }'

第 12 步:使用OPA测试设置

至此,我们可以使用OPA策略对所有设置进行测试了。一旦您运行如下curl命令去访问API网关端点,它会首先在身份验证过程中检查JWT令牌,然后在授权过程中,将使用者和JWT令牌的数据发送到OPA处,以验证角色和权限。显然,任何没有JWT令牌,或不具备已允许角色的请求,都会被拒绝掉。

curl -i http://127.0.0.1:9080/speaker/1/topics -H
'Authorization: {API_CONSUMER_TOKEN}'
curl -i http://127.0.0.1:9080/speaker/1/topics -H

'Authorization: {API_CONSUMER_TOKEN}'
curl -i http://127.0.0.1:9080/speaker/1/topics -H 'Authorization: {API_CONSUMER_TOKEN}'

小结

在本文中,我们通过自定义一个简单的策略逻辑,展示了如何根据API使用者的角色和权限,来允许或禁止API资源的访问。同时,我们也演示了如何从APISIX发送的JWT令牌负载、或使用者的对象中,提取策略文件里与API使用者相关的信息,以最终实现OPA和Apache APISIX的RBAC效果。

原文标题:RBAC With API Gateway and Open Policy Agent (OPA) ,作者:Bobur Umurzokov

© 版权声明
THE END
喜欢就支持一下吧
点赞0

Warning: mysqli_query(): (HY000/3): Error writing file '/tmp/MYY4Vddr' (Errcode: 28 - No space left on device) in /www/wwwroot/583.cn/wp-includes/class-wpdb.php on line 2345
admin的头像-五八三
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

图形验证码
取消
昵称代码图片