聊聊APISIX Ingress 认证使用

身份认证在日常生活当中是非常常见的一项功能,大家平时基本都会接触到,Apache APISIX 作为一个 API
网关,目前已开启与各种插件功能的适配合作,插件库也比较丰富,目前已经可与大量身份认证相关的插件进行搭配处理,如下图所示。

聊聊APISIX Ingress 认证使用插图亿华云

基础认证插件比如 Key-Auth、Basic-Auth,他们是通过账号密码的方式进行认证。复杂一些的认证插件如 Hmac-Auth、JWT-Auth,如
Hmac-Auth 通过对请求信息做一些加密,生成一个签名,当 API 调用方将这个签名携带到 APISIX,APISIX
会以相同的算法计算签名,只有当签名方和应用调用方认证相同时才予以通过。其他则是一些通用认证协议和联合第三方组件进行合作的认证协议,例如
OpenID-Connect 身份认证机制,以及 LDAP 认证等。

APISIX 还可以针对每一个 Consumer (即调用方应用)去做不同级别的插件配置。如下图所示,我们创建了两个消费者 Consumer
A、Consumer B,我们将 Consumer A 应用到应用1,则后续应用1的访问将会开启 Consumer A 的这部分插件,例如 IP
黑白名单,限制并发数量等。将 Consumer B 应用到应用2 ,由于开启了 http-log 插件,则应用2的访问日志将会通过 HTTP
的方式发送到日志系统进行收集。

聊聊APISIX Ingress 认证使用插图1亿华云

basic-auth

首先我们来了解下最简单的基本认证在 APISIX 中是如何使用的。basic-auth 是一个认证插件,它需要与 Consumer
一起配合才能工作。添加 Basic Auth 到一个 Service 或 Route,然后 Consumer
将其用户名和密码添加到请求头中以验证其请求。

首先我们需要在 APISIX Consumer 消费者中增加 basic auth 认证配置,为其指定用户名和密码,我们这里在 APISIX
Ingress 中,可以通过 ApisixConsumer 资源对象进行配置,比如这里我们为前面的 nexus 实例应用添加一个基本认证,如下所示:

# nexus-basic-auth.yaml

apiVersion: apisix.apache.org/v2alpha1

kind: ApisixConsumer

metadata:

name: nexusBauth

spec:

authParameter:

basicAuth:

value:

username: admin

password: admin321

ApisixConsumer 资源对象中只需要配置 authParameter 认证参数即可,目前只支持 BasicAuth 与 KeyAuth
两种认证类型,在 basicAuth 下面可以通过 value 可直接去配置相关的 username 和 password,也可以直接使用 Secret
资源对象进行配置,比起明文配置会更安全一些。

然后在 ApisixRoute 中添加 authentication,将其开启并指定认证类型即可,就可以实现使用 Consumer
去完成相关配置认证,如下所示:

apiVersion: apisix.apache.org/v2beta2

kind: ApisixRoute

metadata:

name: nexus

namespace: default

spec:

http:

- name: root

match:

hosts:

- ops.qikqiak.com

paths:

- "/nexus*"

- "/static/*"

- "/service/*"

plugins:

- name: proxy-rewrite

enable: true

config:

regex_uri: ["^/nexus(/|$)(.*)", "/$2"]

- name: redirect

enable: true

config:

regex_uri: ["^(/nexus)$", "$1/"]

- name: redirect

enable: true

config:

http_to_https: true

backends:

- serviceName: nexus

servicePort: 8081

authentication: # 开启 basic auth 认证

enable: true

type: basicAuth

直接更新上面的资源即可开启 basic auth 认证了,在 Dashboard 上也可以看到创建了一个 Consumer:

聊聊APISIX Ingress 认证使用插图2亿华云

然后我们可以进行如下的测试来进行验证:

# 缺少 Authorization header

➜ curl -i http://ops.qikqiak.com/nexus/

HTTP/1.1 401 Unauthorized

Date: Tue, 11 Jan 2022 07:44:49 GMT

Content-Type: text/plain; charset=utf-8

Transfer-Encoding: chunked

Connection: keep-alive

WWW-Authenticate: Basic realm=.

Server: APISIX/2.10.0

{"message":"Missing authorization in request"}

# 用户名不存在

➜ curl -i -ubar:bar http://ops.qikqiak.com/nexus/

HTTP/1.1 401 Unauthorized

Date: Tue, 11 Jan 2022 07:45:07 GMT

Content-Type: text/plain; charset=utf-8

Transfer-Encoding: chunked

Connection: keep-alive

Server: APISIX/2.10.0

{"message":"Invalid user key in authorization"}

# 成功请求

➜ curl -uadmin:admin321 http://ops.qikqiak.com/nexus/

301 Move

THE END
Copyright © 2024 亿华云