配置 JWT 身份认证
JSON Web Token(JWT)身份认证是一种常用的无状态身份认证方式。与简单 API Key 不同,JWT 可以携带声明,网关无需 为每个请求查询其他系统即可验证这些声明。
API7 网关中的 jwt-auth插件会根据所配置的消费者凭证验证传入 JWT 的签名。
本指南介绍常见 JWT 配置流程。有关完整插件字段参考以及声明验证、其他 Token 位置等高级选项,请参阅 jwt-auth。
前置条件
- API7 企业版实例正在运行。
- 已创建网关组且网关实例正在运行。
- 一个 Dashboard Token。
配置 JWT 身份认证
配置 JWT 身份认证包含三个步骤:
- 创建具有有效上游的服务。
- 创建启用
jwt-auth的路由。 - 创建消费者并挂载 JWT 凭据。
第 1 步:创建具有上游的服务
- Admin API
- ADC
curl -k "https://localhost:7443/apisix/admin/services/jwt-auth-httpbin-service?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "jwt-auth-httpbin-service",
"upstream": {
"type": "roundrobin",
"scheme": "http",
"nodes": [
{
"host": "httpbin.org",
"port": 80,
"weight": 100
}
]
}
}'
adc.yaml
services:
- name: jwt-auth-httpbin-service
upstream:
name: default
scheme: http
nodes:
- host: httpbin.org
port: 80
weight: 100
routes:
- name: jwt-auth-route
uris:
- /anything/jwt-auth
methods:
- GET
plugins:
jwt-auth: {}
consumers:
- username: jwt-auth-consumer
credentials:
- name: jwt-auth-consumer-cred
type: jwt-auth
config:
key: user-1-identity
secret: my-shared-secret
adc sync -f adc.yaml
第 2 步:创建路由并启用 jwt-auth
- Admin API
- ADC
curl -k "https://localhost:7443/apisix/admin/routes/jwt-auth-route?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "jwt-auth-route",
"paths": ["/anything/jwt-auth"],
"methods": ["GET"],
"service_id": "jwt-auth-httpbin-service",
"plugins": {
"jwt-auth": {}
}
}'
该路由已包含在前面的 adc.yaml 示例中。