update plugins doc (#1305)

This commit is contained in:
澄潭
2024-09-12 21:48:40 +08:00
committed by GitHub
parent 0f9113ed82
commit c7c4ae1da2
80 changed files with 7373 additions and 2368 deletions

View File

@@ -1,16 +1,30 @@
<p>
<a href="README_EN.md">English</a> | 中文
</p>
---
title: Basic 认证
keywords: [higress,basic auth]
description: Basic 认证插件配置参考
---
# 功能说明
## 功能说明
`basic-auth`插件实现了基于 HTTP Basic Auth 标准进行认证鉴权的功能
# 配置字段
## 运行属性
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------- | --------------- | -------- | ------ | ---------------------------------------------------- |
| `consumers` | array of object | 必填 | - | 配置服务的调用者,用于对请求进行认证 |
| `_rules_` | array of object | 选填 | - | 配置特定路由或域名的访问权限列表,用于对请求进行鉴权 |
插件执行阶段:`认证阶段`
插件执行优先级:`320`
## 配置字段
**注意:**
- 在一个规则里,鉴权配置和认证配置不可同时存在
- 对于通过认证鉴权的请求请求的header会被添加一个`X-Mse-Consumer`字段,用以标识调用者的名称。
### 认证配置
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------- | --------------- | -------- | ------ | ---------------------------------------------------- |
| `global_auth` | bool | 选填(**仅实例级别配置** | - | 只能在实例级别配置若配置为true则全局生效认证机制; 若配置为false则只对做了配置的域名和路由生效认证机制若不配置则仅当没有域名和路由配置时全局生效兼容老用户使用习惯。 |
| `consumers` | array of object | 必填 | - | 配置服务的调用者,用于对请求进行认证 |
`consumers`中每一项的配置字段说明如下:
@@ -19,51 +33,49 @@
| `credential` | string | 必填 | - | 配置该consumer的访问凭证 |
| `name` | string | 必填 | - | 配置该consumer的名称 |
`_rules_` 中每一项的配置字段说明如下:
### 鉴权配置(非必需)
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ---------------- | --------------- | ------------------------------------------------- | ------ | -------------------------------------------------- |
| `_match_route_` | array of string | 选填,`_match_route_``_match_domain_`中选填一项 | - | 配置要匹配的路由名称 |
| `_match_domain_` | array of string | 选填,`_match_route_``_match_domain_`中选填一项 | - | 配置要匹配的域名 |
| `allow` | array of string | 必填 | - | 对于符合匹配条件的请求配置允许访问的consumer名称 |
**注意:**
- 若不配置`_rules_`字段,则默认对当前网关实例的所有路由开启认证;
- 对于通过认证鉴权的请求请求的header会被添加一个`X-Mse-Consumer`字段,用以标识调用者的名称。
## 配置示例
# 配置示例
## 对特定路由或域名开启认证和鉴权
### 全局配置认证和路由粒度进行鉴权
以下配置将对网关特定路由或域名开启 Basic Auth 认证和鉴权,注意凭证信息中的用户名和密码之间使用":"分隔,`credential`字段不能重复
在实例级别做如下插件配置:
```yaml
# 使用 _rules_ 字段进行细粒度规则配置
consumers:
- credential: 'admin:123456'
name: consumer1
- credential: 'guest:abc'
name: consumer2
_rules_:
# 规则一:按路由名称匹配生效
- _match_route_:
- route-a
- route-b
allow:
- consumer1
# 规则二:按域名匹配生效
- _match_domain_:
- "*.example.com"
- test.com
allow:
- consumer2
global_auth: false
```
此例 `_match_route_` 中指定的 `route-a``route-b` 即在创建网关路由时填写的路由名称,当匹配到这两个路由时,将允许`name``consumer1`的调用者访问,其他调用者不允许访问;
route-a 和 route-b 这两个路由做如下配置:
此例 `_match_domain_` 中指定的 `*.example.com``test.com` 用于匹配请求的域名,当发现域名匹配时,将允许`name``consumer2`的调用者访问,其他调用者不允许访问。
```yaml
allow:
- consumer1
```
### 根据该配置,下列请求可以允许访问:
对 *.example.com 和 test.com 在这两个域名做如下配置:
```yaml
allow:
- consumer2
```
若是在控制台进行配置,此例指定的 `route-a``route-b` 即在控制台创建路由时填写的路由名称,当匹配到这两个路由时,将允许`name``consumer1`的调用者访问,其他调用者不允许访问;
此例指定的 `*.example.com``test.com` 用于匹配请求的域名,当发现域名匹配时,将允许`name``consumer2`的调用者访问,其他调用者不允许访问。
根据该配置,下列请求可以允许访问:
**请求指定用户名密码**
@@ -77,7 +89,7 @@ curl -H 'Authorization: Basic YWRtaW46MTIzNDU2' http://xxx.hello.com/test
认证鉴权通过后请求的header中会被添加一个`X-Mse-Consumer`字段,在此例中其值为`consumer1`,用以标识调用方的名称
### 下列请求将拒绝访问:
下列请求将拒绝访问:
**请求未提供用户名密码返回401**
```bash
@@ -93,22 +105,10 @@ curl -u admin:abc http://xxx.hello.com/test
curl -u guest:abc http://xxx.hello.com/test
```
## 网关实例级别开启
## 相关错误码
以下配置未指定`_rules_`字段,因此将对网关实例级别开启 Basic Auth 认证
```yaml
consumers:
- credential: 'admin:123456'
name: consumer1
- credential: 'guest:abc'
name: consumer2
```
# 相关错误码
| HTTP 状态码 | 出错信息 | 原因说明 |
| ----------- | ------------------------------------------------------------------------------ | ---------------------- |
| HTTP 状态码 | 出错信息 | 原因说明 |
| ----------- |--------------------------------------------------------------------------------| ---------------------- |
| 401 | Request denied by Basic Auth check. No Basic Authentication information found. | 请求未提供凭证 |
| 401 | Request denied by Basic Auth check. Invalid username and/or password | 请求凭证无效 |
| 403 | Request denied by Basic Auth check. Unauthorized consumer | 请求的调用方无访问权限 |
| 401 | Request denied by Basic Auth check. Invalid username and/or password. | 请求凭证无效 |
| 403 | Request denied by Basic Auth check. Unauthorized consumer. | 请求的调用方无访问权限 |

View File

@@ -1,117 +1,99 @@
<p>
English | <a href="README.md">中文</a>
</p>
---
title: Basic Authentication
keywords: [higress,basic auth]
description: Basic authentication plugin configuration reference
---
## Function Description
The `basic-auth` plugin implements authentication and authorization based on the HTTP Basic Auth standard.
# Description
`basic-auth` plugin implements the function of authentication based on the HTTP Basic Auth standard.
# Configuration Fields
| Name | Type | Requirement | Default Value | Description |
| ----------- | --------------- | -------- | ------ | ---------------------------------------------------- |
| `consumers` | array of object | Required | - | Caller of the service for authentication of requests |
| `_rules_` | array of object | Optional | - | Configure access permission list for specific routes or domains to authenticate requests |
Filed descriptions of `consumers` items:
| Name | Type | Requirement | Default Value | Description |
| ------------ | ------ | ----------- | ------------- | ------------------------------------- |
| `credential` | string | Required | - | Credential for this consumer's access |
| `name` | string | Required | - | Name of this consumer |
Configuration field descriptions for each item in `_rules_` are as follows:
| Field Name | Data Type | Requirement | Default | Description |
| ---------------- | --------------- | ------------------------------------------------- | ------ | -------------------------------------------------- |
| `_match_route_` | array of string | One of `_match_route_` or `_match_domain_` | - | Configure the routes to match for request authorization |
| `_match_domain_` | array of string | One of `_match_route_` , `_match_domain_` | - | Configure the domains to match for request authorization |
| `allow` | array of string | Required | - | Configure the consumer names allowed to access requests that match the match condition |
## Operation Attributes
Plugin execution stage: `Authentication Phase`
Plugin execution priority: `320`
## Configuration Fields
**Note:**
- In one rule, authentication configurations and authorization configurations cannot coexist.
- For requests that pass authentication, the request header will include an `X-Mse-Consumer` field to identify the caller's name.
- If the `_rules_` field is not configured, authentication is enabled for all routes of the current gateway instance by default;
- For authenticated requests, `X-Mse-Consumer` field will be added to the request header to identify the name of the caller.
### Authentication Configuration
| Name | Data Type | Requirements | Default Value | Description |
| ------------- | ---------------- | ------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `global_auth` | bool | Optional (**instance-level only**) | - | Can only be configured at the instance level. If set to true, the authentication mechanism will take effect globally; if set to false, it will only take effect for the configured domains and routes. If not configured, it will only take effect globally when there are no domain and route configurations (compatible with old user habits). |
| `consumers` | array of object | Required | - | Configures the service callers for request authentication. |
# Configuration Samples
## Enable Authentication and Authorization for specific routes or domains
The following configuration will enable Basic Auth authentication and authorization for specific routes or domains of the gateway. Note that the username and password in the credential information are separated by a ":", and the `credential` field cannot be repeated.
Each configuration field in `consumers` is described as follows:
| Name | Data Type | Requirements | Default Value | Description |
| ------------ | --------- | ------------ | ------------- | ------------------------------- |
| `credential` | string | Required | - | Configures the access credentials for this consumer. |
| `name` | string | Required | - | Configures the name of this consumer. |
### Authorization Configuration (Optional)
| Name | Data Type | Requirements | Default Value | Description |
| ---------------- | ---------------- | ---------------------------------------------------- | -------------- | -------------------------------------------------------- |
| `allow` | array of string | Required | - | Configures the consumer names allowed to access for matching requests. |
## Configuration Example
### Global Authentication and Route Granularity Authorization
The following configuration will enable Basic Auth authentication and authorization for specific routes or domains of the gateway. Note that the username and password in the credential information are separated by ":", and the `credential` field cannot be duplicated.
Make the following plugin configuration at the instance level:
```yaml
# use the _rules_ field for fine-grained rule configuration.
consumers:
- credential: 'admin:123456'
name: consumer1
- credential: 'guest:abc'
name: consumer2
_rules_:
# rule 1: match by the route name.
- _match_route_:
- route-a
- route-b
allow:
- consumer1
# rule 2: match by the domain.
- _match_domain_:
- "*.example.com"
- test.com
allow:
- consumer2
global_auth: false
```
In this sample, `route-a` and `route-b` specified in `_match_route_` are the route names filled in when creating gateway routes. When these two routes are matched, the caller with `name` as `consumer1` is allowed to access, and other callers are not allowed to access.
The `*.example.com` and `test.com` specified in `_match_domain_` are used to match the domain name of the request. When the domain name is matched, the caller with `name` as `consumer2` is allowed to access, and other callers are not allowed to access.
For routes `route-a` and `route-b`, configure as follows:
```yaml
allow:
- consumer1
```
For the domains `*.example.com` and `test.com`, configure as follows:
```yaml
allow:
- consumer2
```
### According to this configuration, the following requests are allowed:
If configured in the console, the specified `route-a` and `route-b` refer to the route names filled in when creating the routes in the console. When matching these two routes, callers with the name `consumer1` will be allowed access, while other callers will not.
**Requests with specified username and password**
The specified `*.example.com` and `test.com` are used to match the request domain. When a match is found, callers with the name `consumer2` will be allowed access, while other callers will not.
Based on this configuration, the following requests may be allowed access:
**Request with specified username and password**
```bash
# Assuming the following request will match with route-a
# Use -u option of curl to specify the credentials
# Assuming the following request matches the route-a route
# Using curl's -u parameter to specify
curl -u admin:123456 http://xxx.hello.com/test
# Or specify the Authorization request header directly with the credentials in base64 encoding
# Or directly specify the Authorization request header with the username and password encoded in base64
curl -H 'Authorization: Basic YWRtaW46MTIzNDU2' http://xxx.hello.com/test
```
A `X-Mse-Consumer` field will be added to the headers of the request, and its value in this example is `consumer1`, used to identify the name of the caller when passed authentication and authorization.
After successful authentication, the request header will have an added `X-Mse-Consumer` field, which in this case is `consumer1` to identify the caller's name.
### The following requests will be denied:
**Requests without providing username and password, returning 401**
The following requests will be denied access:
**Request without username and password, returns 401**
```bash
curl http://xxx.hello.com/test
```
**Requests with incorrect username or password, returning 401**
**Request with incorrect username and password, returns 401**
```bash
curl -u admin:abc http://xxx.hello.com/test
```
**Requests matched with a caller who has no access permission, returning 403**
**Caller matched by username and password has no access, returns 403**
```bash
# consumer2 is not in the allow list of route-a
# consumer2 is not in the allow list for route-a
curl -u guest:abc http://xxx.hello.com/test
```
## Enable basic auth for gateway instance
The following configuration does not specify the `_rules_` field, so Basic Auth authentication will be effective for the whole gateway instance.
```yaml
consumers:
- credential: 'admin:123456'
name: consumer1
- credential: 'guest:abc'
name: consumer2
```
# Error Codes
| HTTP Status Code | Error Info | Reason |
| ----------- | ------------------------------------------------------------------------------ | ---------------------- |
| 401 | Request denied by Basic Auth check. No Basic Authentication information found. | Credentials not provided in the request |
| 401 | Request denied by Basic Auth check. Invalid username and/or password | Invalid username and/or password |
| 403 | Request denied by Basic Auth check. Unauthorized consumer | Unauthorized consumer |
## Related Error Codes
| HTTP Status Code | Error Message | Reason Description |
| ---------------- | ------------------------------------------------------------------------------------- | -------------------------------- |
| 401 | Request denied by Basic Auth check. No Basic Authentication information found. | Request did not provide credentials. |
| 401 | Request denied by Basic Auth check. Invalid username and/or password. | Request credentials are invalid. |
| 403 | Request denied by Basic Auth check. Unauthorized consumer. | The caller making the request does not have access. |

View File

@@ -1,11 +1,21 @@
<p>
<a href="README_EN.md"> English </a> | 中文
</p>
---
title: Bot 拦截
keywords: [higress,bot detect]
description: Bot 拦截插件配置参考
---
## 功能说明
# 功能说明
`bot-detect`插件可以用于识别并阻止互联网爬虫对站点资源的爬取
# 配置字段
## 运行属性
插件执行阶段:`授权阶段`
插件执行优先级:`310`
## 配置字段
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
@@ -33,9 +43,9 @@
(CSimpleSpider|Cityreview Robot|CrawlDaddy|CrawlFire|Finderbots|Index crawler|Job Roboter|KiwiStatus Spider|Lijit Crawler|QuerySeekerSpider|ScollSpider|Trends Crawler|USyd-NLP-Spider|SiteCat Webbot|BotName\/\$BotVersion|123metaspider-Bot|1470\.net crawler|50\.nu|8bo Crawler Bot|Aboundex|Accoona-[A-z]{1,30}-Agent|AdsBot-Google(?:-[a-z]{1,30}|)|altavista|AppEngine-Google|archive.{0,30}\.org_bot|archiver|Ask Jeeves|[Bb]ai[Dd]u[Ss]pider(?:-[A-Za-z]{1,30})(?:-[A-Za-z]{1,30}|)|bingbot|BingPreview|blitzbot|BlogBridge|Bloglovin|BoardReader Blog Indexer|BoardReader Favicon Fetcher|boitho.com-dc|BotSeer|BUbiNG|\b\w{0,30}favicon\w{0,30}\b|\bYeti(?:-[a-z]{1,30}|)|Catchpoint(?: bot|)|[Cc]harlotte|Checklinks|clumboot|Comodo HTTP\(S\) Crawler|Comodo-Webinspector-Crawler|ConveraCrawler|CRAWL-E|CrawlConvera|Daumoa(?:-feedfetcher|)|Feed Seeker Bot|Feedbin|findlinks|Flamingo_SearchEngine|FollowSite Bot|furlbot|Genieo|gigabot|GomezAgent|gonzo1|(?:[a-zA-Z]{1,30}-|)Googlebot(?:-[a-zA-Z]{1,30}|)|Google SketchUp|grub-client|gsa-crawler|heritrix|HiddenMarket|holmes|HooWWWer|htdig|ia_archiver|ICC-Crawler|Icarus6j|ichiro(?:/mobile|)|IconSurf|IlTrovatore(?:-Setaccio|)|InfuzApp|Innovazion Crawler|InternetArchive|IP2[a-z]{1,30}Bot|jbot\b|KaloogaBot|Kraken|Kurzor|larbin|LEIA|LesnikBot|Linguee Bot|LinkAider|LinkedInBot|Lite Bot|Llaut|lycos|Mail\.RU_Bot|masscan|masidani_bot|Mediapartners-Google|Microsoft .{0,30} Bot|mogimogi|mozDex|MJ12bot|msnbot(?:-media {0,2}|)|msrbot|Mtps Feed Aggregation System|netresearch|Netvibes|NewsGator[^/]{0,30}|^NING|Nutch[^/]{0,30}|Nymesis|ObjectsSearch|OgScrper|Orbiter|OOZBOT|PagePeeker|PagesInventory|PaxleFramework|Peeplo Screenshot Bot|PlantyNet_WebRobot|Pompos|Qwantify|Read%20Later|Reaper|RedCarpet|Retreiver|Riddler|Rival IQ|scooter|Scrapy|Scrubby|searchsight|seekbot|semanticdiscovery|SemrushBot|Simpy|SimplePie|SEOstats|SimpleRSS|SiteCon|Slackbot-LinkExpanding|Slack-ImgProxy|Slurp|snappy|Speedy Spider|Squrl Java|Stringer|TheUsefulbot|ThumbShotsBot|Thumbshots\.ru|Tiny Tiny RSS|Twitterbot|WhatsApp|URL2PNG|Vagabondo|VoilaBot|^vortex|Votay bot|^voyager|WASALive.Bot|Web-sniffer|WebThumb|WeSEE:[A-z]{1,30}|WhatWeb|WIRE|WordPress|Wotbox|www\.almaden\.ibm\.com|Xenu(?:.s|) Link Sleuth|Xerka [A-z]{1,30}Bot|yacy(?:bot|)|YahooSeeker|Yahoo! Slurp|Yandex\w{1,30}|YodaoBot(?:-[A-z]{1,30}|)|YottaaMonitor|Yowedo|^Zao|^Zao-Crawler|ZeBot_www\.ze\.bz|ZooShot|ZyBorg)(?:[ /]v?(\d+)(?:\.(\d+)(?:\.(\d+)|)|)|)
```
# 配置示例
## 配置示例
## 放行原本命中爬虫规则的请求
### 放行原本命中爬虫规则的请求
```yaml
allow:
- ".*Go-http-client.*"
@@ -44,7 +54,7 @@ allow:
若不作该配置,默认的 Golang 网络库请求会被视做爬虫,被禁止访问
## 增加爬虫判断
### 增加爬虫判断
```yaml
deny:
- "spd-tools.*"
@@ -56,24 +66,3 @@ deny:
curl http://example.com -H 'User-Agent: spd-tools/1.1'
curl http://exmaple.com -H 'User-Agent: spd-tools'
```
## 对特定路由或域名开启
```yaml
# 使用 _rules_ 字段进行细粒度规则配置
_rules_:
# 规则一:按路由名称匹配生效
- _match_route_:
- route-a
- route-b
# 规则二:按域名匹配生效
- _match_domain_:
- "*.example.com"
- test.com
allow:
- ".*Go-http-client.*"
```
此例 `_match_route_` 中指定的 `route-a``route-b` 即在创建网关路由时填写的路由名称,当匹配到这两个路由时,将使用此段配置;
此例 `_match_domain_` 中指定的 `*.example.com``test.com` 用于匹配请求的域名,当发现域名匹配时,将使用此段配置;
配置的匹配生效顺序,将按照 `_rules_` 下规则的排列顺序,匹配第一个规则后生效对应配置,后续规则将被忽略。

View File

@@ -1,22 +1,26 @@
<p>
English | <a href="README.md">中文</a>
</p>
---
title: Bot Detect
keywords: [higress, bot detect]
description: Bot detect plugin configuration reference
---
## Function Description
The `bot-detect` plugin can be used to identify and block internet crawlers from accessing site resources.
# Description
`bot-detect` plugin can be used to identify and prevent web crawlers from crawling websites.
## Running Properties
Plugin Execution Phase: `Authorization Phase`
Plugin Execution Priority: `310`
# Configuration Fields
## Configuration Fields
| Name | Data Type | Required | Default Value | Description |
| ----------------- | ------------------- | --------------| --------------| ---------------------------------------------------------- |
| allow | array of string | Optional | - | Regular expressions to match the User-Agent request header; requests matching will be allowed to access. |
| deny | array of string | Optional | - | Regular expressions to match the User-Agent request header; requests matching will be blocked. |
| blocked_code | number | Optional | 403 | HTTP status code returned when a request is blocked. |
| blocked_message | string | Optional | - | HTTP response body returned when a request is blocked. |
| Name | Type | Requirement | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| allow | array of string | Optional | - | A regular expression to match the User-Agent request header and will allow access if the match hits |
| deny | array of string | Optional | - | A regular expression to match the User-Agent request header and will block the request if the match hits |
| blocked_code | number | Optional | 403 | The HTTP status code returned when a request is blocked |
| blocked_message | string | Optional | - | The HTTP response Body returned when a request is blocked |
The `allow` and `deny` fields can both be left unconfigured, in which case the default crawler identification logic will be executed. Configuring the `allow` field can allow requests that would otherwise hit the default crawler identification logic. Configuring the `deny` field can add additional crawler identification logic.
If field `allow` and field `deny` are not configured at the same time, the default logic to identify crawlers will be executed. By configuring the `allow` field, requests that would otherwise hit the default logic can be allowed. The judgement can be extended by configuring the `deny` field
The default set of crawler judgment regular expressions is as follows
The default crawler identification regular expression set is as follows:
```bash
# Bots General matcher 'name/0.0'
@@ -33,45 +37,23 @@ The default set of crawler judgment regular expressions is as follows
(CSimpleSpider|Cityreview Robot|CrawlDaddy|CrawlFire|Finderbots|Index crawler|Job Roboter|KiwiStatus Spider|Lijit Crawler|QuerySeekerSpider|ScollSpider|Trends Crawler|USyd-NLP-Spider|SiteCat Webbot|BotName\/\$BotVersion|123metaspider-Bot|1470\.net crawler|50\.nu|8bo Crawler Bot|Aboundex|Accoona-[A-z]{1,30}-Agent|AdsBot-Google(?:-[a-z]{1,30}|)|altavista|AppEngine-Google|archive.{0,30}\.org_bot|archiver|Ask Jeeves|[Bb]ai[Dd]u[Ss]pider(?:-[A-Za-z]{1,30})(?:-[A-Za-z]{1,30}|)|bingbot|BingPreview|blitzbot|BlogBridge|Bloglovin|BoardReader Blog Indexer|BoardReader Favicon Fetcher|boitho.com-dc|BotSeer|BUbiNG|\b\w{0,30}favicon\w{0,30}\b|\bYeti(?:-[a-z]{1,30}|)|Catchpoint(?: bot|)|[Cc]harlotte|Checklinks|clumboot|Comodo HTTP\(S\) Crawler|Comodo-Webinspector-Crawler|ConveraCrawler|CRAWL-E|CrawlConvera|Daumoa(?:-feedfetcher|)|Feed Seeker Bot|Feedbin|findlinks|Flamingo_SearchEngine|FollowSite Bot|furlbot|Genieo|gigabot|GomezAgent|gonzo1|(?:[a-zA-Z]{1,30}-|)Googlebot(?:-[a-zA-Z]{1,30}|)|Google SketchUp|grub-client|gsa-crawler|heritrix|HiddenMarket|holmes|HooWWWer|htdig|ia_archiver|ICC-Crawler|Icarus6j|ichiro(?:/mobile|)|IconSurf|IlTrovatore(?:-Setaccio|)|InfuzApp|Innovazion Crawler|InternetArchive|IP2[a-z]{1,30}Bot|jbot\b|KaloogaBot|Kraken|Kurzor|larbin|LEIA|LesnikBot|Linguee Bot|LinkAider|LinkedInBot|Lite Bot|Llaut|lycos|Mail\.RU_Bot|masscan|masidani_bot|Mediapartners-Google|Microsoft .{0,30} Bot|mogimogi|mozDex|MJ12bot|msnbot(?:-media {0,2}|)|msrbot|Mtps Feed Aggregation System|netresearch|Netvibes|NewsGator[^/]{0,30}|^NING|Nutch[^/]{0,30}|Nymesis|ObjectsSearch|OgScrper|Orbiter|OOZBOT|PagePeeker|PagesInventory|PaxleFramework|Peeplo Screenshot Bot|PlantyNet_WebRobot|Pompos|Qwantify|Read%20Later|Reaper|RedCarpet|Retreiver|Riddler|Rival IQ|scooter|Scrapy|Scrubby|searchsight|seekbot|semanticdiscovery|SemrushBot|Simpy|SimplePie|SEOstats|SimpleRSS|SiteCon|Slackbot-LinkExpanding|Slack-ImgProxy|Slurp|snappy|Speedy Spider|Squrl Java|Stringer|TheUsefulbot|ThumbShotsBot|Thumbshots\.ru|Tiny Tiny RSS|Twitterbot|WhatsApp|URL2PNG|Vagabondo|VoilaBot|^vortex|Votay bot|^voyager|WASALive.Bot|Web-sniffer|WebThumb|WeSEE:[A-z]{1,30}|WhatWeb|WIRE|WordPress|Wotbox|www\.almaden\.ibm\.com|Xenu(?:.s|) Link Sleuth|Xerka [A-z]{1,30}Bot|yacy(?:bot|)|YahooSeeker|Yahoo! Slurp|Yandex\w{1,30}|YodaoBot(?:-[A-z]{1,30}|)|YottaaMonitor|Yowedo|^Zao|^Zao-Crawler|ZeBot_www\.ze\.bz|ZooShot|ZyBorg)(?:[ /]v?(\d+)(?:\.(\d+)(?:\.(\d+)|)|)|)
```
# Configuration Samples
## Release Requests that would otherwise Hit the Crawler Rules
## Configuration Example
### Allowing Requests That Hit the Crawler Rules
```yaml
allow:
- ".*Go-http-client.*"
```
Without this configuration, the default Golang web library request will be treated as a crawler and access will be denied.
If this configuration is not made, requests from the default Golang network library will be treated as crawlers and blocked.
## Add Crawler Judgement
### Adding Crawler Identification
```yaml
deny:
- "spd-tools.*"
```
According to this configuration, the following requests will be denied:
With this configuration, the following requests will be blocked:
```bash
curl http://example.com -H 'User-Agent: spd-tools/1.1'
curl http://exmaple.com -H 'User-Agent: spd-tools'
```
## Only Enabled for Specific Routes or Domains
```yaml
# Use _rules_ field for fine-grained rule configurations
_rules_:
# Rule 1: Match by route name
- _match_route_:
- route-a
- route-b
# Rule 2: Match by domain
- _match_domain_:
- "*.example.com"
- test.com
allow:
- ".*Go-http-client.*"
```
In the rule sample of `_match_route_`, `route-a` and `route-b` are the route names provided when creating a new gateway route. When the current route names matches the configuration, the rule following shall be applied.
In the rule sample of `_match_domain_`, `*.example.com` and `test.com` are the domain names used for request matching. When the current domain name matches the configuration, the rule following shall be applied.
All rules shall be checked following the order of items in the `_rules_` field, The first matched rule will be applied. All remained will be ignored.

View File

@@ -1,11 +1,19 @@
<p>
<a href="README_EN.md"> English </a> | 中文
</p>
---
title: 自定义应答
keywords: [higress,customn response]
description: 自定义应答插件配置参考
---
# 功能说明
## 功能说明
`custom-response`插件支持配置自定义的响应,包括自定义 HTTP 应答状态码、HTTP 应答头,以及 HTTP 应答 Body。可以用于 Mock 响应,也可以用于判断特定状态码后给出自定义应答,例如在触发网关限流策略时实现自定义响应。
# 配置字段
## 运行属性
插件执行阶段:`认证阶段`
插件执行优先级:`910`
## 配置字段
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
@@ -14,9 +22,9 @@
| body | string | 选填 | - | 自定义 HTTP 应答 Body |
| enable_on_status | array of number | 选填 | - | 匹配原始状态码,生成自定义响应,不填写时,不判断原始状态码 |
# 配置示例
## 配置示例
## Mock 应答场景
### Mock 应答场景
```yaml
status_code: 200
@@ -38,7 +46,7 @@ Content-Length: 17
{"hello":"world"}
```
## 触发限流时自定义响应
### 触发限流时自定义响应
```yaml
enable_on_status:
@@ -58,27 +66,3 @@ Location: https://example.com
从而实现基于浏览器 302 重定向机制,将限流后的用户引导到其他页面,比如可以是一个 CDN 上的静态页面。
如果希望触发限流时,正常返回其他应答,参考 Mock 应答场景配置相应的字段即可。
## 对特定路由或域名开启
```yaml
# 使用 _rules_ 字段进行细粒度规则配置
_rules_:
# 规则一:按路由名称匹配生效
- _match_route_:
- route-a
- route-b
body: "{\"hello\":\"world\"}"
# 规则二:按域名匹配生效
- _match_domain_:
- "*.example.com"
- test.com
enable_on_status:
- 429
status_code: 200
headers:
- Content-Type=application/json
body: "{\"errmsg\": \"rate limited\"}"
```
此例 `_match_route_` 中指定的 `route-a``route-b` 即在创建网关路由时填写的路由名称,当匹配到这两个路由时,将使用此段配置;
此例 `_match_domain_` 中指定的 `*.example.com``test.com` 用于匹配请求的域名,当发现域名匹配时,将使用此段配置;
配置的匹配生效顺序,将按照 `_rules_` 下规则的排列顺序,匹配第一个规则后生效对应配置,后续规则将被忽略。

View File

@@ -1,84 +1,54 @@
<p>
English | <a href="README.md">中文</a>
</p>
---
title: Custom Response
keywords: [higress, custom response]
description: Custom response plugin configuration reference
---
## Function Description
The `custom-response` plugin supports the configuration of custom responses, including custom HTTP response status codes, HTTP response headers, and HTTP response bodies. It can be used for Mock responses or for providing custom responses based on specific status codes, such as implementing custom responses when triggering the gateway rate-limiting policy.
# Description
`custom-response` plugin implements a function of sending custom responses, including custom HTTP response status codes, HTTP response headers and HTTP response body, which can be used in the scenarios of response mocking and sending a custom response for specific status codes, such as customizing the response for rate-limited requests.
## Running Attributes
Plugin Execution Phase: `Authentication Phase`
# Configuration Fields
Plugin Execution Priority: `910`
| Name | Type | Requirement | Default Value | Description |
## Configuration Fields
| Name | Data Type | Requirements | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| status_code | number | Optional | 200 | Custom HTTP response status code |
| headers | array of string | Optional | - | Custom HTTP response header. Key and value shall be separated using `=`. |
| headers | array of string | Optional | - | Custom HTTP response headers, keys and values separated by `=` |
| body | string | Optional | - | Custom HTTP response body |
| enable_on_status | array of number | Optional | - | The original response status code to match. Generate the custom response only the actual status code matches the configuration. Ignore the status code match if left unconfigured. |
# Configuration Samples
## Mock Responses
| enable_on_status | array of number | Optional | - | Match original status codes to generate custom responses; if not specified, the original status code is not checked |
## Configuration Example
### Mock Response Scenario
```yaml
status_code: 200
headers:
- Content-Type=application/json
- Hello=World
body: "{\"hello\":\"world\"}"
```
According to the configuration above, all the requests will get the following custom response:
With this configuration, the request will return the following custom response:
```text
HTTP/1.1 200 OK
Content-Type: application/json
Hello: World
Content-Length: 17
{"hello":"world"}
```
## Send a Custom Response when Rate-Limited
### Custom Response on Rate Limiting
```yaml
enable_on_status:
enable_on_status:
- 429
status_code: 302
headers:
- Location=https://example.com
```
When rate-limited, normally gateway will return a status code of `429` . Now, rate-limited requests will get the following custom response:
When the gateway rate limiting is triggered, it generally returns the `429` status code, and the request will return the following custom response:
```text
HTTP/1.1 302 Found
Location: https://example.com
```
This achieves the goal of redirecting users who have been rate-limited to another page based on the browser's 302 redirect mechanism, which could be a static page on a CDN.
So based on the 302 redirecting mechanism provided by browsers, this can redirect rate-limited users to other pages, for example, a static page hosted on CDN.
If you'd like to send other responses when rate-limited, please add other fields into the configuration, referring to the Mock Responses scenario.
## Only Enabled for Specific Routes or Domains
```yaml
# Use _rules_ field for fine-grained rule configurations
_rules_:
# Rule 1: Match by route name
- _match_route_:
- route-a
- route-b
body: "{\"hello\":\"world\"}"
# Rule 2: Match by domain
- _match_domain_:
- "*.example.com"
- test.com
enable_on_status:
- 429
status_code: 200
headers:
- Content-Type=application/json
body: "{\"errmsg\": \"rate limited\"}"
```
In the rule sample of `_match_route_`, `route-a` and `route-b` are the route names provided when creating a new gateway route. When the current route names matches the configuration, the rule following shall be applied.
In the rule sample of `_match_domain_`, `*.example.com` and `test.com` are the domain names used for request matching. When the current domain name matches the configuration, the rule following shall be applied.
All rules shall be checked following the order of items in the `_rules_` field, The first matched rule will be applied. All remained will be ignored.
If you wish to return other responses normally when rate limiting is triggered, just refer to the Mock response scenario to configure the relevant fields accordingly.

View File

@@ -1,13 +1,32 @@
# 功能说明
---
title: HMAC 认证
keywords: [higress,hmac auth]
description: HMAC 认证插件配置参考
---
## 功能说明
`hmac-auth`插件实现了基于 HMAC 算法为 HTTP 请求生成不可伪造的签名,并基于签名实现身份认证和鉴权
# 配置字段
## 运行属性
插件执行阶段:`认证阶段`
插件执行优先级:`330`
## 配置字段
**注意:**
- 在一个规则里,鉴权配置和认证配置不可同时存在
- 对于通过认证鉴权的请求请求的header会被添加一个`X-Mse-Consumer`字段,用以标识调用者的名称。
### 认证配置
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ------------- | --------------- | -------- | ------ | ------------------------------------------------------------------------------------------------------------------- |
| `global_auth` | bool | 选填(**仅实例级别配置** | - | 只能在实例级别配置若配置为true则全局生效认证机制; 若配置为false则只对做了配置的域名和路由生效认证机制若不配置则仅当没有域名和路由配置时全局生效兼容老用户使用习惯。 |
| `consumers` | array of object | 必填 | - | 配置服务的调用者,用于对请求进行认证 |
| `date_offset` | number | 选填 | - | 配置允许的客户端最大时间偏移,单位为秒,根据请求头`Date`解析客户端 UTC 时间,可用于避免请求重放;未配置时,不做校验 |
| `_rules_` | array of object | 选填 | - | 配置特定路由或域名的访问权限列表,用于对请求进行鉴权 |
`consumers`中每一项的配置字段说明如下:
@@ -17,24 +36,21 @@
| `secret` | string | 必填 | - | 配置用于生成签名的secret |
| `name` | string | 必填 | - | 配置该consumer的名称 |
`_rules_` 中每一项的配置字段说明如下:
### 鉴权配置(非必需)
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ---------------- | --------------- | ------------------------------------------------- | ------ | -------------------------------------------------- |
| `_match_route_` | array of string | 选填`_match_route_``_match_domain_`中选填一项 | - | 配置要匹配的路由名称 |
| `_match_domain_` | array of string | 选填,`_match_route_``_match_domain_`中选填一项 | - | 配置要匹配的域名 |
| `allow` | array of string | 必填 | - | 对于符合匹配条件的请求配置允许访问的consumer名称 |
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------- | --------------- | ------------------------------------------- | ------ | ----------------------------------------------------------- |
| `allow` | array of string | 选填(**非实例级别配置**) | - | 只能在路由或域名等细粒度规则上配置,对于符合匹配条件的请求,配置允许访问的 consumer从而实现细粒度的权限控制 |
**注意:**
- 若不配置`_rules_`字段,则默认对当前网关实例的所有路由开启认证;
- 对于通过认证鉴权的请求请求的header会被添加一个`X-Mse-Consumer`字段,用以标识调用者的名称。
# 配置示例
## 配置示例
以下配置将对网关特定路由或域名开启 Hmac Auth 认证和鉴权,注意`key`字段不能重复
### 全局配置认证和路由粒度进行鉴权
在实例级别做如下插件配置, 注意`key`字段不能重复:
## 对特定路由或域名开启
```yaml
global_auth: false
consumers:
- key: appKey-example-1
secret: appSecret-example-1
@@ -42,34 +58,33 @@ consumers:
- key: appKey-example-2
secret: appSecret-example-2
name: consumer-2
# 使用 _rules_ 字段进行细粒度规则配置
_rules_:
# 规则一:按路由名称匹配生效
- _match_route_:
- route-a
- route-b
allow:
- consumer-1
# 规则二:按域名匹配生效
- _match_domain_:
- "*.example.com"
- test.com
allow:
- consumer-2
```
每条匹配规则下的`allow`字段用于指定该匹配条件下允许访问的调用者列表;
此例 `_match_route_` 中指定的 `route-a``route-b` 即在创建网关路由时填写的路由名称,当匹配到这两个路由时,将允许`name``consumer-1`的调用者访问,其他调用者不允许访问;
此例 `_match_domain_` 中指定的 `*.example.com``test.com` 用于匹配请求的域名,当发现域名匹配时,将允许`name``consumer-2`的调用者访问,其他调用者不允许访问;
认证成功后请求的header中会被添加一个`X-Mse-Consumer`字段,其值为调用方的名称,例如`consumer-1`
## 网关实例级别开启
以下配置将对网关实例级别开启 Hamc Auth 认证
route-a和route-b两个路由做如下插件配置
```yaml
allow:
- consumer1
```
在*.example.com和test.com两个域名做如下插件配置
```yaml
allow:
- consumer2
```
若是在控制台进行配置此例指定的route-a和route-b即在创建网关路由时填写的路由名称当匹配到这两个路由时将允许name为consumer1的调用者访问其他调用者不允许访问。
此例指定的*.example.com和test.com用于匹配请求的域名当发现域名匹配时将允许name为consumer2的调用者访问其他调用者不被允许访问。
### 网关实例级别开启
以下配置将对网关实例级别开启 Hamc Auth 认证,所有请求均需要经过认证后才能访问。
```yaml
global_auth: true
consumers:
- key: appKey-example-1
secret: appSecret-example-1
@@ -80,18 +95,18 @@ consumers:
```
# 签名机制说明
## 签名机制说明
## 配置准备
### 配置准备
如上指引,在插件配置中配置生成和验证签名需要用的凭证配置
- key: 用于请求头 `x-ca-key` 中设置
- secret: 用于生成请求签名
## 客户端签名生成方式
### 客户端签名生成方式
### 流程简介
#### 流程简介
客户端生成签名一共分三步处理:
@@ -104,7 +119,7 @@ consumers:
如下图所示:
![](https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1745707061/p188113.png)
### 签名串提取流程
#### 签名串提取流程
客户端需要从Http请求中提取出关键数据组合成一个签名串生成的签名串的格式如下
@@ -160,7 +175,7 @@ Path + "?" + Key1 + "=" + Value1 + "&" + Key2 + "=" + Value2 + ... "&" + KeyN +
4. Query和Form存在数组参数时key相同value不同的参数 取第一个Value参与签名计算
### 签名串提取示例
#### 签名串提取示例
初始的HTTP请求
```text
@@ -190,7 +205,7 @@ x-ca-timestamp:1525872629832
/http2test/test?param1=test&password=123456789&username=xiaoming
```
### 签名计算流程
#### 签名计算流程
客户端从HTTP请求中提取出关键数据组装成签名串后需要对签名串进行加密及编码处理形成最终的签名
@@ -206,7 +221,7 @@ String sign = Base64.encodeBase64String(result);
总结一下,就是将 `stringToSign` 使用UTF-8解码后得到Byte数组然后使用加密算法对Byte数组进行加密然后使用Base64算法进行编码形成最终的签名。
### 添加签名流程
#### 添加签名流程
客户端需要将以下四个Header放在HTTP请求中传输给API网关进行签名校验
@@ -238,9 +253,9 @@ content-length:33
username=xiaoming&password=123456789
```
## 服务端签名验证方式
### 服务端签名验证方式
### 流程简介
#### 流程简介
服务器验证客户端签名一共分四步处理:
@@ -256,7 +271,7 @@ username=xiaoming&password=123456789
![](https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1745707061/p188116.png)
## 签名排错方法
### 签名排错方法
网关签名校验失败时会将服务端的签名串StringToSign放到HTTP Response的Header中返回到客户端Key为X-Ca-Error-Message用户只需要将本地计算的签名串StringToSign与服务端返回的签名串进行对比即可找到问题
@@ -269,7 +284,7 @@ X-Ca-Error-Message: Server StringToSign:`GET#application/json##application/json
```
# 相关错误码
## 相关错误码
| HTTP 状态码 | 出错信息 | 原因说明 |
| ----------- | ---------------------- | -------------------------------------------------------------------------------- |
@@ -281,5 +296,3 @@ X-Ca-Error-Message: Server StringToSign:`GET#application/json##application/json
| 413 | Request Body Too Large | 请求 Body 超过限制大小32 MB |
| 413 | Payload Too Large | 请求 Body 超过全局配置 DownstreamConnectionBufferLimits |
| 403 | Unauthorized Consumer | 请求的调用方无访问权限 |

View File

@@ -1,76 +1,71 @@
# Function Description
The `hmac-auth` plugin implements the generation of tamper-proof signatures for HTTP requests based on HMAC algorithm, and uses the signature for identity authentication and authorization.
---
title: HMAC Authentication
keywords: [higress,hmac auth]
description: HMAC Authentication plugin configuration reference
---
## Function Description
The `hmac-auth` plugin implements the generation of tamper-proof signatures for HTTP requests based on the HMAC algorithm, and performs authentication and authorization based on the signature.
# Configuration Fields
## Running Attributes
Plugin execution phase: `Authentication phase`
Plugin execution priority: `330`
| Name | Data Type | Required | Default | Description |
| ------------- | --------------- | -------------| ------ | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `consumers` | array of object | Required | - | Configures the caller of the service to authenticate the request. |
| `date_offset` | number | Optional | - | Configures the maximum allowed time deviation of the client, in seconds. It is used to parse the client's UTC time from `the Date` header of the request, and can be used to prevent replay attacks. If not configured, no validation is performed. |
| `_rules_` | array of object | Optional | - | Configures the access control list for specific routes or domains, used for authorization of requests. |
## Configuration Fields
**Note:**
- In a rule, authentication and authorization configurations cannot coexist.
- For requests that pass authentication and authorization, the request header will be added with an `X-Mse-Consumer` field to identify the caller's name.
The configuration fields for each item in `consumers` are as follows :
### Authentication Configuration
| Name | Data Type | Requirement | Default Value | Description |
| ------------- | ---------------- | ------------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `global_auth` | bool | Optional (**Instance level configuration only**) | - | Can only be configured at the instance level. If set to true, it acts globally; if false, only applies to configured domains and routes. If not configured, it will apply globally only when there are no domain and route configurations (to accommodate old user habits). |
| `consumers` | array of object | Mandatory | - | Configures the callers of the service for request authentication. |
| `date_offset` | number | Optional | - | Configures the maximum allowed client time offset, in seconds; parsed based on the request header `Date`; can be used to prevent request replay; no validation is performed if not configured. |
| Name | Data Type| Required | Default| Description |
| -------- | -------- | ------------ | ------ | ----------------------------------------------------------------------- |
| `key` | string | Required | - | Configures the key extracted from the `x-ca-key` header of the request. |
| `secret` | string | Required | - | Configures the secret used to generate the signature. |
| `name` | string | Required | - | Configures the name of the consumer. |
The configuration fields for each item in `consumers` are as follows:
| Name | Data Type | Requirement | Default Value | Description |
| -------- | --------- | ----------- | ------------- | ------------------------------------------- |
| `key` | string | Mandatory | - | Configures the key extracted from the `x-ca-key` header of the request. |
| `secret` | string | Mandatory | - | Configures the secret used to generate the signature. |
| `name` | string | Mandatory | - | Configures the name of the consumer. |
The configuration fields for each item in `_rules_` are as follows:
### Authorization Configuration (Optional)
| Name | Data Type | Requirement | Default Value | Description |
| ----------- | ---------------- | --------------------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `allow` | array of string | Optional (**Non-instance level configuration**) | - | Can only be configured on granular rules such as routes or domains. For requests that match the conditions, configure the allowed consumers to achieve fine-grained permission control. |
| Name | Data Type | Required | Default | Description |
| ---------------- | --------------- | ------------------------------------------------- | ---------------------------- | -------------------------------------------------- |
| `_match_route_` | array of string | Optional, either `_match_route_` or `_match_domain_` must be provided | - | Configures the name of the route to match. |
| `_match_domain_` | array of string | Optional, either `_match_route_` or `_match_domain_` must be provided | - | Configures the name of the domain to match. |
| `allow` | array of string | Required | - | Configures the name of the consumer to allow for requests that match the specified route or domain. |
**Note**
- If `_rules_` is not configured, authentication is enabled for all routes on the current gateway instance by default
- For requests that pass authentication and authorization, a `X-Mse-Consumer` header will be added to the request headers to identify the name of the consumer.
# Configuration Example
The following configuration enables Hmac Auth authentication and authorization for specific routes or domains on the gateway. Note that the `key` field should not be duplicated.
## Enabling for specific routes or domains
## Configuration Example
### Global Configuration Authentication and Route Granular Authorization
Configure the following plugin settings at the instance level. Note that the `key` field cannot be duplicated:
```yaml
consumers:
global_auth: false
consumers:
- key: appKey-example-1
secret: appSecret-example-1
name: consumer-1
- key: appKey-example-2
secret: appSecret-example-2
name: consumer-2
# Configuring Fine-Grained Rules using _rules_ Field
_rules_:
# Rule 1: Matching by route name.
- _match_route_:
- route-a
- route-b
allow:
- consumer-1
# Rule 2: Applies based on domain name matching.
- _match_domain_:
- "*.example.com"
- test.com
allow:
- consumer-2
```
The `allow` field under each matching rule specifies the list of callers allowed to access under that matching condition;
In this example, `route-a` and `route-b` specified in `_match_route_` are the route names filled in when creating the gateway route. When either of these routes is matched, it will allow access to the caller named `consumer-1`, while denying access to other callers
In` _match_domain_`, `*.example.com` and `test.com` are used to match the requested domain name. When a match is found, it will allow access to the caller named `consumer-2`, while denying access to other callers
Upon successful authentication, the `X-Mse-Consumer` field will be added to the request header with the value set to the caller's name, such as `consumer-1`.。
## Enable at the Gateway Instance Level
The following configuration enables HMAC authentication at the gateway instance level.
For route-a and route-b, configure the plugin as follows:
```yaml
consumers:
allow:
- consumer1
```
For the two domains *.example.com and test.com, configure as follows:
```yaml
allow:
- consumer2
```
If configured in the console, the specified route names route-a and route-b correspond to the route names filled in when creating the gateway routes. When matched to these two routes, access will be allowed for the caller named consumer1, while other callers will not be allowed access.
The specified *.example.com and test.com are used to match the domains of the requests. When a domain match is found, access will be allowed for the caller named consumer2, while other callers will not be allowed access.
### Gateway Instance Level Activation
The following configuration will enable HMAC Auth authentication at the gateway instance level, requiring all requests to undergo authentication before access.
```yaml
global_auth: true
consumers:
- key: appKey-example-1
secret: appSecret-example-1
name: consumer-1
@@ -79,34 +74,24 @@ consumers:
name: consumer-2
```
## Signature Mechanism Description
### Configuration Preparation
As mentioned above, configure the credentials required for generating and verifying signatures in the plugin settings.
- key: to be set in the request header `x-ca-key`.
- secret: used for generating request signatures.
# Description of Signing Mechanism
### Client Signature Generation Process
#### Overview
The client generates a signature through three main steps:
1. Extract key data from the original request to create a string for signing.
2. Encrypt the key data signing string using the algorithm and the configured `secret` to obtain the signature.
3. Include all relevant headers for the signature into the original HTTP request to form the final HTTP request.
## Configuration Preparation
As mentioned in the guide above, configure the credential settings required for generating and validating signatures in the plugin configuration.
- key: Used for setting in the request header `x-ca-key`.
- secret: Used for generating the request signature.
## Client Signature Generation Method
### Overview of the Process
The process for generating a signature on the client side consists of three steps:
1. Extracting key data from the original request to obtain a string to be signed.
2. Using encryption algorithms and the configured `secret` to encrypt the key data signing string and obtain a signature.
3. Adding all headers related to the signature to the original HTTP request to obtain the final HTTP request.
As shown below :
As shown in the figure below:
![](https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1745707061/p188113.png)
### Process for Extracting Signing String
To generate a signature, the client needs to extract key data from the HTTP request and combine it into a signing string. The format of the generated signing string is as follows:
#### Signing String Extraction Process
The client needs to extract key data from the HTTP request, combine it into a signing string, which has the following format:
```text
HTTPMethod
Accept
@@ -116,54 +101,38 @@ Date
Headers
PathAndParameters
```
The signing string consists of the above 7 fields separated by \n. If Headers is empty, no \n is needed. If other fields are empty, the \n should still be retained. The signature is case-sensitive. Below are the rules for extracting each field:
- HTTPMethod: The HTTP method used in the request, in all capital letters, such as POST.
- Accept: The value of the Accept header in the request, which can be empty. It is recommended to explicitly set the Accept header. When Accept is empty, some HTTP clients will set the default value of `*/*`, which may cause signature verification to fail.
- Content-MD5: The value of the Content-MD5 header in the request, which can be empty. It is only calculated when there is a non-form body in the request. The following is a reference calculation method for Content-MD5 values in
The seven fields above constitute the entire signing string, separated by newline characters `\n`. If Headers is empty, no newline is needed; other fields should retain `\n` if empty. The signature is case-sensitive. Below are the extraction rules for each field:
- HTTPMethod: The HTTP method, all uppercase (e.g., POST).
- Accept: The value of the Accept header in the request, can be empty. It is recommended to explicitly set the Accept Header. When Accept is empty, some HTTP clients may set a default value of `*/*`, resulting in a signature verification failure.
- Content-MD5: The value of the Content-MD5 header in the request, can be empty. It is calculated only if there is a Body in the request and it is not in Form format. Heres a reference calculation method for the Content-MD5 value in Java:
```java
String content-MD5 = Base64.encodeBase64(MD5(bodyStream.getbytes("UTF-8")));
String content-MD5 = Base64.encodeBase64(MD5(bodyStream.getBytes("UTF-8")));
```
- Content-Type: The value of the Content-Type header in the request, which can be empty.
- Date: The value of the Date header in the request. When the` date_offset` configuration is not enabled, it can be empty. Otherwise, it will be used for time offset verification.
- Headers: Users can select specific headers to participate in the signature. There are the following rules for concatenating the signature string with headers:
- The keys of the headers participating in the signature calculation are sorted in alphabetical order and concatenated as follows:
- Content-Type: The value of the Content-Type header in the request, can be empty.
- Date: The value of the Date header in the request. If the `date_offset` configuration is not turned on, it can be empty; otherwise, it will be used for time offset verification.
- Headers: Users can select specific headers to participate in the signature. The rules for concatenating the signing header string are as follows:
- The Keys of the headers participating in the signature calculation are concatenated after being sorted lexicographically, as follows:
```text
HeaderKey1 + ":" + HeaderValue1 + "\n"\+
HeaderKey2 + ":" + HeaderValue2 + "\n"\+
HeaderKey1 + ":" + HeaderValue1 + "\n" +
HeaderKey2 + ":" + HeaderValue2 + "\n" +
...
HeaderKeyN + ":" + HeaderValueN + "\n"
```
- If the value of a header is empty, it will participate in the signature with the `HeaderKey+":"+"\n"` only, and the key and english colon should be retained.
- The set of keys for all headers participating in the signature is separated by a comma and placed in the `X-Ca-Signature-Headers header`.
- If the Value of a certain header is empty, use HeaderKey + ":" + "\n" to participate in the signature, retaining the Key and the colon.
- The collection of all participating header Keys is placed in the Header with the key X-Ca-Signature-Headers, separated by commas.
- The following headers are not included in the header signature calculation: X-Ca-Signature, X-Ca-Signature-Headers, Accept, Content-MD5, Content-Type, Date.
- PathAndParameters: This field contains all parameters in the path, query, and form. The specific format is as follows:
- PathAndParameters: This field includes Path, Query, and all parameters in Form, specifically organized as follows:
```text
Path + "?" + Key1 + "=" + Value1 + "&" + Key2 + "=" + Value2 + ... "&" + KeyN + "=" + ValueN
```
Note:
1. The Key of Query and Form parameters should be sorted lexicographically before being concatenated as above.
2. If Query and Form parameters are empty, just use Path without adding `?`.
3. If the Value of parameters is empty, only the Key should be retained in the signature, the equal sign does not need to be added.
4. In the case of array parameters (parameters with the same key but different values), only the first Value should be used for signature calculation.
Notes:
1. The keys of the query and form parameter pairs are sorted alphabetically, and the same format as above is used for concatenation.
2. If there are no query and form parameters, use the path directly without adding `?` .
3. If the value of a parameter is empty, only the key will be included in the signature. The equal sign should not be included in the signature.
4. If there are array parameters in the query or form (parameters with the same key but different values), only the first value should be included in the signature calculation.
### Example of Extracting Signing String
The initial HTTP request :
#### Signing String Extraction Example
Initial HTTP request:
```text
POST /http2test/test?param1=test HTTP/1.1
host:api.aliyun.com
@@ -177,8 +146,7 @@ x-ca-nonce:c9f15cbf-f4ac-4a6c-b54d-f51abf4b5b44
content-length:33
username=xiaoming&password=123456789
```
The correct generated signature string is :
The generated correct signing string is:
```text
POST
application/json; charset=utf-8
@@ -190,13 +158,10 @@ x-ca-signature-method:HmacSHA256
x-ca-timestamp:1525872629832
/http2test/test?param1=test&password=123456789&username=xiaoming
```
#### Signature Calculation Process
After the client assembles the key data extracted from the HTTP request into a signing string, it needs to encrypt the signing string and encode it to form the final signature.
### Signature Calculation Process
After extracting the key data from the HTTP request and assembling it into a signature string, the client needs to encrypt and encode the signature string to form the final signature.
The specific encryption format is as follows, where `stringToSign` is the extracted signature string, `secret` is the one filled in the plugin configuration, and `sign` is the final generated signature:
The specific encryption form is as follows, where `stringToSign` is the extracted signing string, `secret` is the one filled in the plugin configuration, and `sign` is the final generated signature:
```java
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
byte[] secretBytes = secret.getBytes("UTF-8");
@@ -204,23 +169,16 @@ hmacSha256.init(new SecretKeySpec(secretBytes, 0, secretBytes.length, "HmacSHA25
byte[] result = hmacSha256.doFinal(stringToSign.getBytes("UTF-8"));
String sign = Base64.encodeBase64String(result);
```
To summarize, the `stringToSign` is decoded using UTF-8 to obtain a Byte array, then the encryption algorithm is applied to the Byte array, and finally, the Base64 algorithm is used for encoding, forming the final signature.
In summary, the `stringToSign` is decoded using UTF-8 to obtain a Byte array. Then, an encryption algorithm is used to encrypt the Byte array, and finally, the Base64 algorithm is used to encode the encrypted data, resulting in the final signature.
### The Process of Adding a Signature
The client needs to include the following four headers in the HTTP request to be transmitted to the API gateway for signature verification:
- x-ca-key: The value is the APP Key and is required.
- x-ca-signature-method: The signature algorithm, the value can be HmacSHA256 or HmacSHA1, optional. The default value is HmacSHA256.
- x-ca-signature-headers: The collection of keys for all signature headers, separated by commas. Optional.
- x-ca-signature: The signature and it is required.
Here is an example of a complete HTTP request with a signature :
#### Adding the Signature Process
The client needs to include the following four headers in the HTTP request to transmit to the API gateway for signature verification:
- x-ca-key: The APP Key, mandatory.
- x-ca-signature-method: The signature algorithm, can be HmacSHA256 or HmacSHA1, optional, default is HmacSHA256.
- x-ca-signature-headers: The collection of all signature header Keys, separated by commas, optional.
- x-ca-signature: The signature, mandatory.
Below is an example of the entire HTTP request carrying the signature:
```text
POST /http2test/test?param1=test HTTP/1.1
host:api.aliyun.com
@@ -239,48 +197,35 @@ content-length:33
username=xiaoming&password=123456789
```
## Server-side Signature Verification Method
### Server-side Signature Verification Method
#### Overview
The server verifies the client signature through four main steps:
1. Extract key data from the received request to create a signing string.
2. Read the `key` from the received request and query the corresponding `secret`.
3. Encrypt the key data signing string using the algorithm and the `secret` to obtain the signature.
4. Read the client signature from the received request and compare the server-side signature with the client-side signature for consistency.
### Overview of the Process
The server-side signature verification of the client's request involves four steps :
1. Extract crucial data from the received request to obtain a string for signing.
2. Retrieve the `key` from the received request and use it to query its corresponding `secret`.
3. Encrypt the string for signing using the encryption algorithm and `secret`.
4. Retrieve the client's signature from the received request, and compare the consistency of the server-side signature with the client's signature.
As shown below :
As shown in the figure below:
![](https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/1745707061/p188116.png)
### Signature Troubleshooting Method
When the gateway signature verification fails, the server's signing string (StringToSign) will be returned in the HTTP Response header to the client, with the key: X-Ca-Error-Message. The user only needs to compare the locally computed signing string (StringToSign) with the signing string returned by the server to find the issue.
## Troubleshooting Signature Errors
When the gateway signature verification fails, the server-side signing string (StringToSign) will be returned to the client in the HTTP Response Header. The key is X-Ca-Error-Message. Users only need to compare the locally calculated signing string with the server-side signing string returned to locate the problem;
If the StringToSign on the server side is consistent with that on the client side, please check whether the APP Secret used for signature calculation is correct
Because line breaks cannot be represented in HTTP headers, all line breaks in the StringToSign are replaced with #, as shown below:
If the StringToSign from the server and the client are consistent, please check whether the APP Secret used for signature calculation is correct.
Since HTTP headers cannot express line breaks, the line breaks in the StringToSign have been replaced with `#`, as shown below:
```text
X-Ca-Error-Message: Server StringToSign:`GET#application/json##application/json##X-Ca-Key:200000#X-Ca-Timestamp:1589458000000#/app/v1/config/keys?keys=TEST`
```
# Related Error Codes
| HTTP Status Code | Error Message | Reason |
| ----------- | ---------------------- | -------------------------------------------------------------------------------- |
| 401 | Invalid Key | The x-ca-key request header is not provided or is invalid. |
| 401 | Empty Signature | The x-ca-signature request header does not contain a signature. |
| 400 | Invalid Signature | The x-ca-signature request header contains a signature that does not match the server-calculated signature. |
| 400 | Invalid Content-MD5 | The content-md5 request header is incorrect. |
| 400 | Invalid Date | The time offset calculated based on the date request header exceeds the configured date_offset. |
| 413 | Request Body Too Large | The request body exceeds the size limit of 32 MB. |
| 413 | Payload Too Large | The request body exceeds the DownstreamConnectionBufferLimits global configuration. |
| 403 | Unauthorized Consumer | The requesting party does not have access permission. |
## Related Error Codes
| HTTP Status Code | Error Message | Reasoning |
| ---------------- | --------------------- | --------------------------------------------- |
| 401 | Invalid Key | The request header did not provide x-ca-key, or x-ca-key is invalid. |
| 401 | Empty Signature | The request header did not provide the x-ca-signature signing string. |
| 400 | Invalid Signature | The x-ca-signature signing string in the request header does not match the signature calculated by the server. |
| 400 | Invalid Content-MD5 | The Content-MD5 header in the request is incorrect. |
| 400 | Invalid Date | The time offset calculated based on the Date header in the request exceeds the configured date_offset. |
| 413 | Request Body Too Large| The request Body exceeds the maximum size of 32 MB. |
| 413 | Payload Too Large | The request Body exceeds the global configured DownstreamConnectionBufferLimits. |
| 403 | Unauthorized Consumer | The calling party does not have access permissions for the request. |

View File

@@ -1,17 +1,216 @@
# 功能说明
---
title: JWT 认证
keywords: [higress,jwt auth]
description: JWT 认证插件配置参考
---
## 功能说明
`jwt-auth`插件实现了基于JWT(JSON Web Tokens)进行认证鉴权的功能支持从HTTP请求的URL参数、请求头、Cookie字段解析JWT同时验证该Token是否有权限访问。
本插件和`安全能力->认证鉴权`中JWT认证的区别是额外提供了调用方身份识别的能力支持对不同调用方配置不同的JWT凭证。
# 详细说明
## 运行属性
## 1、基于token的认证
插件执行阶段:`认证阶段`
插件执行优先级:`340`
### 1.1 简介
## 配置字段
**注意:**
- 在一个规则里,鉴权配置和认证配置不可同时存在
- 对于通过认证鉴权的请求请求的header会被添加一个`X-Mse-Consumer`字段,用以标识调用者的名称。
### 认证配置
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------- | --------------- | ------------------------------------------- | ------ | ----------------------------------------------------------- |
| `global_auth` | bool | 选填(**仅实例级别配置** | - | 只能在实例级别配置若配置为true则全局生效认证机制; 若配置为false则只对做了配置的域名和路由生效认证机制若不配置则仅当没有域名和路由配置时全局生效兼容老用户使用习惯。 |
| `consumers` | array of object | 必填 | - | 配置服务的调用者,用于对请求进行认证 |
`consumers`中每一项的配置字段说明如下:
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------------------- | ----------------- | -------- | ------------------------------------------------- | ------------------------ |
| `name` | string | 必填 | - | 配置该consumer的名称 |
| `jwks` | string | 必填 | - | https://www.rfc-editor.org/rfc/rfc7517 指定的json格式字符串是由验证JWT中签名的公钥或对称密钥组成的Json Web Key Set |
| `issuer` | string | 必填 | - | JWT的签发者需要和payload中的iss字段保持一致 |
| `claims_to_headers` | array of object | 选填 | - | 抽取JWT的payload中指定字段设置到指定的请求头中转发给后端 |
| `from_headers` | array of object | 选填 | {"name":"Authorization","value_prefix":"Bearer "} | 从指定的请求头中抽取JWT |
| `from_params` | array of string | 选填 | access_token | 从指定的URL参数中抽取JWT |
| `from_cookies` | array of string | 选填 | - | 从指定的cookie中抽取JWT |
| `clock_skew_seconds` | number | 选填 | 60 | 校验JWT的exp和iat字段时允许的时钟偏移量单位为秒 |
| `keep_token` | bool | 选填 | ture | 转发给后端时是否保留JWT |
**注意:**
- 只有当`from_headers`,`from_params`,`from_cookies`均未配置时,才会使用默认值
`from_headers` 中每一项的配置字段说明如下:
| 名称 | 数据类型 | 填写要求| 默认值 | 描述 |
| ---------------- | --------------- | ------- | ------ | --------------------------------------------------------- |
| `name` | string | 必填 | - | 抽取JWT的请求header |
| `value_prefix` | string | 必填 | - | 对请求header的value去除此前缀剩余部分作为JWT |
`claims_to_headers` 中每一项的配置字段说明如下:
| 名称 | 数据类型 | 填写要求| 默认值 | 描述 |
| ---------------- | --------------- | ------- | ------ | --------------------------------------------------------- |
| `claim` | string | 必填 | - | JWT payload中的指定字段要求必须是字符串或无符号整数类型 |
| `header` | string | 必填 | - | 从payload取出字段的值设置到这个请求头中转发给后端 |
| `override` | bool | 选填 | true | true时存在同名请求头会进行覆盖false时追加同名请求头 |
### 鉴权配置(非必需)
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------- | --------------- | ------------------------------------------- | ------ | ----------------------------------------------------------- |
| `allow` | array of string | 选填(**非实例级别配置**) | - | 只能在路由或域名等细粒度规则上配置,对于符合匹配条件的请求,配置允许访问的 consumer从而实现细粒度的权限控制 |
## 配置示例
### 全局配置认证和路由粒度进行鉴权
注意如果一个JWT能匹配多个`jwks`,则按照配置顺序命中第一个匹配的`consumer`
在实例级别做如下插件配置:
```yaml
global_auth: false
consumers:
- name: consumer1
issuer: abcd
jwks: |
{
"keys": [
{
"kty": "oct",
"kid": "123",
"k": "hM0k3AbXBPpKOGg__Ql2Obcq7s60myWDpbHXzgKUQdYo7YCRp0gUqkCnbGSvZ2rGEl4YFkKqIqW7mTHdj-bcqXpNr-NOznEyMpVPOIlqG_NWVC3dydBgcsIZIdD-MR2AQceEaxriPA_VmiUCwfwL2Bhs6_i7eolXoY11EapLQtutz0BV6ZxQQ4dYUmct--7PLNb4BWJyQeWu0QfbIthnvhYllyl2dgeLTEJT58wzFz5HeNMNz8ohY5K0XaKAe5cepryqoXLhA-V-O1OjSG8lCNdKS09OY6O0fkyweKEtuDfien5tHHSsHXoAxYEHPFcSRL4bFPLZ0orTt1_4zpyfew",
"alg": "HS256"
}
]
}
- name: consumer2
issuer: abc
jwks: |
{
"keys": [
{
"kty": "RSA",
"e": "AQAB",
"use": "sig",
"kid": "123",
"alg": "RS256",
"n": "i0B67f1jggT9QJlZ_8QL9QQ56LfurrqDhpuu8BxtVcfxrYmaXaCtqTn7OfCuca7cGHdrJIjq99rz890NmYFZuvhaZ-LMt2iyiSb9LZJAeJmHf7ecguXS_-4x3hvbsrgUDi9tlg7xxbqGYcrco3anmalAFxsbswtu2PAXLtTnUo6aYwZsWA6ksq4FL3-anPNL5oZUgIp3HGyhhLTLdlQcC83jzxbguOim-0OEz-N4fniTYRivK7MlibHKrJfO3xa_6whBS07HW4Ydc37ZN3Rx9Ov3ZyV0idFblU519nUdqp_inXj1eEpynlxH60Ys_aTU2POGZh_25KXGdF_ZC_MSRw"
}
]
}
```
对 route-a 和 route-b 这两个路由做如下配置:
```yaml
allow:
- consumer1
```
对 *.example.com 和 test.com 在这两个域名做如下配置:
```yaml
allow:
- consumer2
```
**说明:**
此例指定的route-a和route-b即在创建网关路由时填写的路由名称当匹配到这两个路由时将允许name为consumer1的调用者访问其他调用者不允许访问。
此例指定的*.example.com和test.com用于匹配请求的域名当发现域名匹配时将允许name为consumer2的调用者访问其他调用者不被允许访问。
根据该配置,下列请求可以允许访问:
假设以下请求会匹配到route-a这条路由
**将 JWT 设置在 url 参数中**
```bash
curl 'http://xxx.hello.com/test?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMyJ9.eyJpc3MiOiJhYmNkIiwic3ViIjoidGVzdCIsImlhdCI6MTY2NTY2MDUyNywiZXhwIjoxODY1NjczODE5fQ.-vBSV0bKeDwQcuS6eeSZN9dLTUnSnZVk8eVCXdooCQ4'
```
**将 JWT 设置在 http 请求头中**
```bash
curl http://xxx.hello.com/test -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMyJ9.eyJpc3MiOiJhYmNkIiwic3ViIjoidGVzdCIsImlhdCI6MTY2NTY2MDUyNywiZXhwIjoxODY1NjczODE5fQ.-vBSV0bKeDwQcuS6eeSZN9dLTUnSnZVk8eVCXdooCQ4'
```
认证鉴权通过后请求的header中会被添加一个`X-Mse-Consumer`字段,在此例中其值为`consumer1`,用以标识调用方的名称
下列请求将拒绝访问:
**请求未提供JWT返回401**
```bash
curl http://xxx.hello.com/test
```
**根据请求提供的JWT匹配到的调用者无访问权限返回403**
```bash
# consumer1不在*.example.com的allow列表里
curl 'http://xxx.example.com/test' -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMyJ9.eyJpc3MiOiJhYmNkIiwic3ViIjoidGVzdCIsImlhdCI6MTY2NTY2MDUyNywiZXhwIjoxODY1NjczODE5fQ.-vBSV0bKeDwQcuS6eeSZN9dLTUnSnZVk8eVCXdooCQ4'
```
#### 网关实例级别开启
以下配置将对网关实例级别开启 JWT Auth 认证,所有请求均需要经过认证后才能访问。
```yaml
global_auth: true
consumers:
- name: consumer1
issuer: abcd
jwks: |
{
"keys": [
{
"kty": "oct",
"kid": "123",
"k": "hM0k3AbXBPpKOGg__Ql2Obcq7s60myWDpbHXzgKUQdYo7YCRp0gUqkCnbGSvZ2rGEl4YFkKqIqW7mTHdj-bcqXpNr-NOznEyMpVPOIlqG_NWVC3dydBgcsIZIdD-MR2AQceEaxriPA_VmiUCwfwL2Bhs6_i7eolXoY11EapLQtutz0BV6ZxQQ4dYUmct--7PLNb4BWJyQeWu0QfbIthnvhYllyl2dgeLTEJT58wzFz5HeNMNz8ohY5K0XaKAe5cepryqoXLhA-V-O1OjSG8lCNdKS09OY6O0fkyweKEtuDfien5tHHSsHXoAxYEHPFcSRL4bFPLZ0orTt1_4zpyfew",
"alg": "HS256"
}
]
}
- name: consumer2
issuer: abc
jwks: |
{
"keys": [
{
"kty": "RSA",
"e": "AQAB",
"use": "sig",
"kid": "123",
"alg": "RS256",
"n": "i0B67f1jggT9QJlZ_8QL9QQ56LfurrqDhpuu8BxtVcfxrYmaXaCtqTn7OfCuca7cGHdrJIjq99rz890NmYFZuvhaZ-LMt2iyiSb9LZJAeJmHf7ecguXS_-4x3hvbsrgUDi9tlg7xxbqGYcrco3anmalAFxsbswtu2PAXLtTnUo6aYwZsWA6ksq4FL3-anPNL5oZUgIp3HGyhhLTLdlQcC83jzxbguOim-0OEz-N4fniTYRivK7MlibHKrJfO3xa_6whBS07HW4Ydc37ZN3Rx9Ov3ZyV0idFblU519nUdqp_inXj1eEpynlxH60Ys_aTU2POGZh_25KXGdF_ZC_MSRw"
}
]
}
```
## 常见错误码说明
| HTTP 状态码 | 出错信息 | 原因说明 |
| ----------- | ---------------------- | -------------------------------------------------------------------------------- |
| 401 | Jwt missing | 请求头未提供JWT |
| 401 | Jwt expired | JWT已经过期 |
| 401 | Jwt verification fails | JWT payload校验失败如iss不匹配 |
| 403 | Access Denied | 无权限访问当前路由 |
## 详细说明
### 1、基于token的认证
#### 1.1 简介
很多对外开放的API需要识别请求者的身份并据此判断所请求的资源是否可以返回给请求者。token就是一种用于身份验证的机制基于这种机制应用不需要在服务端保留用户的认证信息或者会话信息可实现无状态、分布式的Web应用授权为应用的扩展提供了便利。
### 1.2 流程描述
#### 1.2 流程描述
![](https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/2336348951/p135822.png)
@@ -35,13 +234,13 @@
在这个整个过程中, 网关利用token认证机制实现了用户使用自己的用户体系对自己API进行授权的能力。下面我们就要介绍网关实现token认证所使用的结构化令牌Json Web Token(JWT)。
### 1.3 JWT
#### 1.3 JWT
#### 1.3.1 简介
##### 1.3.1 简介
Json Web TokeJWT是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准RFC7519。JWT一般可以用作独立的身份验证令牌可以包含用户标识、用户角色和权限等信息以便于从资源服务器获取资源也可以增加一些额外的其它业务逻辑所必须的声明信息特别适用于分布式站点的登录场景。
#### 1.3.2 JWT的构成
##### 1.3.2 JWT的构成
`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ`
@@ -119,11 +318,11 @@ var signature = HMACSHA256(encodedString, '$secret');
将这三部分用 . 连接成一个完整的字符串,就构成了 1.3.2 节最开始的JWT示例。
#### 1.3.3 时效
##### 1.3.3 时效
网关会验证token中的exp字段一旦这个字段过期了网关会认为这个token无效而将请求直接打回。过期时间这个值必须设置。
#### 1.3.4 JWT的几个特点
##### 1.3.4 JWT的几个特点
1. JWT 默认是不加密,不能将秘密数据写入 JWT。
2. JWT 不仅可以用于认证,也可以用于交换信息。有效使用 JWT可以降低服务器查询数据库的次数。
@@ -131,9 +330,9 @@ var signature = HMACSHA256(encodedString, '$secret');
4. JWT 本身包含了认证信息一旦泄露任何人都可以获得该令牌的所有权限。为了减少盗用JWT 的有效期应该设置得比较短。对于一些比较重要的权限,使用时应该再次对用户进行认证。
5. 为了减少盗用JWT 不应该使用 HTTP 协议明码传输要使用HTTPS 协议传输。
## 2、用户系统如何应用JWT插件保护API
### 2、用户系统如何应用JWT插件保护API
### 2.1 生成一对JWKJSON Web 密钥)
#### 2.1 生成一对JWKJSON Web 密钥)
**方法一、在线生成:**
@@ -162,7 +361,7 @@ final String publicKeyString = rsaJsonWebKey.toJson(JsonWebKey.OutputControlLeve
final String privateKeyString = rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);
```
### 2.2 使用JWK中的私钥实现颁发token 的认证服务
#### 2.2 使用JWK中的私钥实现颁发token 的认证服务
需要使用2.1节中在线生成的 Keypair JSON字符串三个方框内的第一个或者本地生成的 privateKeyString JSON字符串作为私钥来颁发token用于授权可信的用户访问受保护的API具体实现可以参考下方示例。 向客户颁发token的形式由用户根据具体的业务场景决定可以将颁发token的功能部署到生产环境配置成普通API后由访问者通过用户名密码获得也可以直接在本地环境生成token 后,直接拷贝给指定用户使用。
@@ -216,187 +415,3 @@ public class GenerateJwtDemo {
}
}
```
# 插件配置说明
## 配置字段
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------- | --------------- | ------------------------------------------- | ------ | ----------------------------------------------------------- |
| `consumers` | array of object | 必填 | - | 配置服务的调用者,用于对请求进行认证 |
| `_rules_` | array of object | 选填 | - | 配置特定路由或域名的访问权限列表,用于对请求进行鉴权 |
`consumers`中每一项的配置字段说明如下:
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------------------- | ----------------- | -------- | ------------------------------------------------- | ------------------------ |
| `name` | string | 必填 | - | 配置该consumer的名称 |
| `jwks` | string | 必填 | - | https://www.rfc-editor.org/rfc/rfc7517 指定的json格式字符串是由验证JWT中签名的公钥或对称密钥组成的Json Web Key Set |
| `issuer` | string | 必填 | - | JWT的签发者需要和payload中的iss字段保持一致 |
| `claims_to_headers` | array of object | 选填 | - | 抽取JWT的payload中指定字段设置到指定的请求头中转发给后端 |
| `from_headers` | array of object | 选填 | {"name":"Authorization","value_prefix":"Bearer "} | 从指定的请求头中抽取JWT |
| `from_params` | array of string | 选填 | access_token | 从指定的URL参数中抽取JWT |
| `from_cookies` | array of string | 选填 | - | 从指定的cookie中抽取JWT |
| `clock_skew_seconds` | number | 选填 | 60 | 校验JWT的exp和iat字段时允许的时钟偏移量单位为秒 |
| `keep_token` | bool | 选填 | ture | 转发给后端时是否保留JWT |
**注意:**
- 只有当`from_headers`,`from_params`,`from_cookies`均未配置时,才会使用默认值
`from_headers` 中每一项的配置字段说明如下:
| 名称 | 数据类型 | 填写要求| 默认值 | 描述 |
| ---------------- | --------------- | ------- | ------ | --------------------------------------------------------- |
| `name` | string | 必填 | - | 抽取JWT的请求header |
| `value_prefix` | string | 必填 | - | 对请求header的value去除此前缀剩余部分作为JWT |
`claims_to_headers` 中每一项的配置字段说明如下:
| 名称 | 数据类型 | 填写要求| 默认值 | 描述 |
| ---------------- | --------------- | ------- | ------ | --------------------------------------------------------- |
| `claim` | string | 必填 | - | JWT payload中的指定字段要求必须是字符串或无符号整数类型 |
| `header` | string | 必填 | - | 从payload取出字段的值设置到这个请求头中转发给后端 |
| `override` | bool | 选填 | true | true时存在同名请求头会进行覆盖false时追加同名请求头 |
`_rules_` 中每一项的配置字段说明如下:
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ---------------- | --------------- | ------------------------------------------------- | ------ | -------------------------------------------------- |
| `_match_route_` | array of string | 选填,`_match_route_``_match_domain_`中选填一项 | - | 配置要匹配的路由名称 |
| `_match_domain_` | array of string | 选填,`_match_route_``_match_domain_`中选填一项 | - | 配置要匹配的域名 |
| `allow` | array of string | 必填 | - | 对于符合匹配条件的请求配置允许访问的consumer名称 |
**注意:**
- 若不配置`_rules_`字段,则默认对当前网关实例的所有路由开启认证;
- 对于通过认证鉴权的请求请求的header会被添加一个`X-Mse-Consumer`字段,用以标识调用者的名称。
## 配置示例
### 对特定路由或域名开启
以下配置将对网关特定路由或域名开启 Jwt Auth 认证和鉴权注意如果一个JWT能匹配多个`jwks`,则按照配置顺序命中第一个匹配的`consumer`
```yaml
consumers:
- name: consumer1
issuer: abcd
jwks: |
{
"keys": [
{
"kty": "oct",
"kid": "123",
"k": "hM0k3AbXBPpKOGg__Ql2Obcq7s60myWDpbHXzgKUQdYo7YCRp0gUqkCnbGSvZ2rGEl4YFkKqIqW7mTHdj-bcqXpNr-NOznEyMpVPOIlqG_NWVC3dydBgcsIZIdD-MR2AQceEaxriPA_VmiUCwfwL2Bhs6_i7eolXoY11EapLQtutz0BV6ZxQQ4dYUmct--7PLNb4BWJyQeWu0QfbIthnvhYllyl2dgeLTEJT58wzFz5HeNMNz8ohY5K0XaKAe5cepryqoXLhA-V-O1OjSG8lCNdKS09OY6O0fkyweKEtuDfien5tHHSsHXoAxYEHPFcSRL4bFPLZ0orTt1_4zpyfew",
"alg": "HS256"
}
]
}
- name: consumer2
issuer: abc
jwks: |
{
"keys": [
{
"kty": "RSA",
"e": "AQAB",
"use": "sig",
"kid": "123",
"alg": "RS256",
"n": "i0B67f1jggT9QJlZ_8QL9QQ56LfurrqDhpuu8BxtVcfxrYmaXaCtqTn7OfCuca7cGHdrJIjq99rz890NmYFZuvhaZ-LMt2iyiSb9LZJAeJmHf7ecguXS_-4x3hvbsrgUDi9tlg7xxbqGYcrco3anmalAFxsbswtu2PAXLtTnUo6aYwZsWA6ksq4FL3-anPNL5oZUgIp3HGyhhLTLdlQcC83jzxbguOim-0OEz-N4fniTYRivK7MlibHKrJfO3xa_6whBS07HW4Ydc37ZN3Rx9Ov3ZyV0idFblU519nUdqp_inXj1eEpynlxH60Ys_aTU2POGZh_25KXGdF_ZC_MSRw"
}
]
}
# 使用 _rules_ 字段进行细粒度规则配置
_rules_:
# 规则一:按路由名称匹配生效
- _match_route_:
- route-a
- route-b
allow:
- consumer1
# 规则二:按域名匹配生效
- _match_domain_:
- "*.example.com"
- test.com
allow:
- consumer2
```
此例 `_match_route_` 中指定的 `route-a``route-b` 即在创建网关路由时填写的路由名称,当匹配到这两个路由时,将允许`name``consumer1`的调用者访问,其他调用者不允许访问;
此例 `_match_domain_` 中指定的 `*.example.com``test.com` 用于匹配请求的域名,当发现域名匹配时,将允许`name``consumer2`的调用者访问,其他调用者不允许访问。
#### 根据该配置,下列请求可以允许访问:
假设以下请求会匹配到route-a这条路由
**将 JWT 设置在 url 参数中**
```bash
curl 'http://xxx.hello.com/test?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMyJ9.eyJpc3MiOiJhYmNkIiwic3ViIjoidGVzdCIsImlhdCI6MTY2NTY2MDUyNywiZXhwIjoxODY1NjczODE5fQ.-vBSV0bKeDwQcuS6eeSZN9dLTUnSnZVk8eVCXdooCQ4'
```
**将 JWT 设置在 http 请求头中**
```bash
curl http://xxx.hello.com/test -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMyJ9.eyJpc3MiOiJhYmNkIiwic3ViIjoidGVzdCIsImlhdCI6MTY2NTY2MDUyNywiZXhwIjoxODY1NjczODE5fQ.-vBSV0bKeDwQcuS6eeSZN9dLTUnSnZVk8eVCXdooCQ4'
```
认证鉴权通过后请求的header中会被添加一个`X-Mse-Consumer`字段,在此例中其值为`consumer1`,用以标识调用方的名称
#### 下列请求将拒绝访问:
**请求未提供JWT返回401**
```bash
curl http://xxx.hello.com/test
```
**根据请求提供的JWT匹配到的调用者无访问权限返回403**
```bash
# consumer1不在*.example.com的allow列表里
curl 'http://xxx.example.com/test' -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMyJ9.eyJpc3MiOiJhYmNkIiwic3ViIjoidGVzdCIsImlhdCI6MTY2NTY2MDUyNywiZXhwIjoxODY1NjczODE5fQ.-vBSV0bKeDwQcuS6eeSZN9dLTUnSnZVk8eVCXdooCQ4'
```
### 网关实例级别开启
以下配置未指定`_rules_`字段,因此将对网关实例级别开启 JWT Auth 认证
```yaml
consumers:
- name: consumer1
issuer: abcd
jwks: |
{
"keys": [
{
"kty": "oct",
"kid": "123",
"k": "hM0k3AbXBPpKOGg__Ql2Obcq7s60myWDpbHXzgKUQdYo7YCRp0gUqkCnbGSvZ2rGEl4YFkKqIqW7mTHdj-bcqXpNr-NOznEyMpVPOIlqG_NWVC3dydBgcsIZIdD-MR2AQceEaxriPA_VmiUCwfwL2Bhs6_i7eolXoY11EapLQtutz0BV6ZxQQ4dYUmct--7PLNb4BWJyQeWu0QfbIthnvhYllyl2dgeLTEJT58wzFz5HeNMNz8ohY5K0XaKAe5cepryqoXLhA-V-O1OjSG8lCNdKS09OY6O0fkyweKEtuDfien5tHHSsHXoAxYEHPFcSRL4bFPLZ0orTt1_4zpyfew",
"alg": "HS256"
}
]
}
- name: consumer2
issuer: abc
jwks: |
{
"keys": [
{
"kty": "RSA",
"e": "AQAB",
"use": "sig",
"kid": "123",
"alg": "RS256",
"n": "i0B67f1jggT9QJlZ_8QL9QQ56LfurrqDhpuu8BxtVcfxrYmaXaCtqTn7OfCuca7cGHdrJIjq99rz890NmYFZuvhaZ-LMt2iyiSb9LZJAeJmHf7ecguXS_-4x3hvbsrgUDi9tlg7xxbqGYcrco3anmalAFxsbswtu2PAXLtTnUo6aYwZsWA6ksq4FL3-anPNL5oZUgIp3HGyhhLTLdlQcC83jzxbguOim-0OEz-N4fniTYRivK7MlibHKrJfO3xa_6whBS07HW4Ydc37ZN3Rx9Ov3ZyV0idFblU519nUdqp_inXj1eEpynlxH60Ys_aTU2POGZh_25KXGdF_ZC_MSRw"
}
]
}
```
# 常见错误码说明
| HTTP 状态码 | 出错信息 | 原因说明 |
| ----------- | ---------------------- | -------------------------------------------------------------------------------- |
| 401 | Jwt missing | 请求头未提供JWT |
| 401 | Jwt expired | JWT已经过期 |
| 401 | Jwt verification fails | JWT payload校验失败如iss不匹配 |
| 403 | Access Denied | 无权限访问当前路由 |

View File

@@ -1,170 +1,306 @@
# Description
The `jwt-auth` plugin implements authentication and authorization based on JWT (JSON Web Token), supports parsing JWTs from URL parameters, request headers, and Cookie fields from HTTP requests, and verifies whether the token has permission to access.
---
title: JWT Authentication
keywords: [higress,jwt auth]
description: JWT Authentication plugin configuration reference
---
The difference between this plugin and the JWT authentication in `Security Capabilities->Authentication and Authorization` is that it provides additional capabilities for identifying the caller's identity, supporting the configuration of different JWT credentials for different callers.
## Function Description
`jwt-auth` plugin implements authentication and authorization based on JWT (JSON Web Tokens). It supports extracting JWT from HTTP request URL parameters, request headers, and Cookie fields, while verifying whether the Token has the necessary permissions to access the resource.
# Detailed Description
The difference between this plugin and the JWT authentication in `Security Capability -> Authentication and Authorization` is that it additionally provides the capability of identifying the caller's identity, supporting different JWT credentials for different callers.
## 1. Token-based authentication
## Runtime Properties
Plugin execution phase: `Authentication Phase`
Plugin execution priority: `340`
### 1.1 Introduction
Many open APIs need to identify the identity of the caller and determine whether the requested resource can be returned to the caller based on this identity. Token is a mechanism used for identity verification. Based on this mechanism, the application does not need to retain the user's authentication information or session information on the server, which can realize stateless and distributed web application authorization and provide convenience for application extension.
## Configuration Fields
**Note:**
- In one rule, authentication configuration and authorization configuration cannot coexist.
- For requests authenticated through authentication and authorization, the request header will be augmented with an `X-Mse-Consumer` field to identify the caller's name.
### 1.2 Process Description
### Authentication Configuration
| Name | Data Type | Requirements | Default Value | Description |
| ----------- | --------------- | ---------------------------------------------- | ------------- | ----------------------------------------------------------- |
| `global_auth` | bool | Optional (**instance-level configuration only**) | - | Can only be configured at the instance level. If set to true, it will globally enable the authentication mechanism; if set to false, it will only apply to the configured domain names and routes. If not configured, it will only globally take effect when no domain names and routes are configured (to be compatible with old user habits). |
| `consumers` | array of object | Required | - | Configure service consumers for request authentication |
![](process.png)
The configuration fields for each item in `consumers` are as follows:
| Name | Data Type | Requirements | Default Value | Description |
| ----------------------- | ------------------ | ------------ | -------------------------------------------------- | ------------------------------- |
| `name` | string | Required | - | The name of the consumer |
| `jwks` | string | Required | - | JSON format string specified by https://www.rfc-editor.org/rfc/rfc7517, consisting of the public key (or symmetric key) used to verify the JWT signature. |
| `issuer` | string | Required | - | The issuer of the JWT, must match the `iss` field in the payload. |
| `claims_to_headers` | array of object | Optional | - | Extract the specified fields from the JWT payload and set them in the specified request headers to forward to the backend. |
| `from_headers` | array of object | Optional | {"name":"Authorization","value_prefix":"Bearer "} | Extract JWT from the specified request headers. |
| `from_params` | array of string | Optional | access_token | Extract JWT from the specified URL parameters. |
| `from_cookies` | array of string | Optional | - | Extract JWT from the specified cookies. |
| `clock_skew_seconds` | number | Optional | 60 | The allowed clock skew when validating the `exp` and `iat` fields of the JWT, measured in seconds. |
| `keep_token` | bool | Optional | true | Whether to retain the JWT when forwarding to the backend. |
The above figure is the business process sequence diagram when the gateway uses JWT for authentication, and the following we will describe the steps marked in the figure in detail in words:
**Note:**
- The default values will only be used when `from_headers`, `from_params`, and `from_cookies` are not all configured.
The configuration fields for each item in `from_headers` are as follows:
| Name | Data Type | Requirements | Default Value | Description |
| --------------- | ---------------- | ------------ | ------------- | ----------------------------------------------- |
| `name` | string | Required | - | Extract JWT from the request header. |
| `value_prefix` | string | Required | - | Remove the prefix from the request header value, with the remaining part serving as the JWT. |
1. The client initiates an authentication request to the API gateway, usually carrying the end user's username and password in the request;
The configuration fields for each item in `claims_to_headers` are as follows:
| Name | Data Type | Requirements | Default Value | Description |
| --------------- | ---------------- | ------------ | ------------- | --------------------------------------------- |
| `claim` | string | Required | - | The specified field in the JWT payload, must be a string or unsigned integer type. |
| `header` | string | Required | - | The value of the field extracted from the payload is set to this request header and forwarded to the backend. |
| `override` | bool | Optional | true | If true, existing headers with the same name will be overridden; if false, they will be appended. |
2. The gateway forwards the request directly to the backend service;
### Authorization Configuration (Optional)
| Name | Data Type | Requirements | Default Value | Description |
| ----------- | --------------- | ---------------------------------------------- | ------------- | ----------------------------------------------------------------------------------------------------- |
| `allow` | array of string | Optional (**not instance-level configuration**) | - | Can only be configured on fine-grained rules such as routes or domain names, allowing specified consumers to access matching requests for fine-grained permission control. |
3. The backend service reads the authentication information (such as the username and password) in the request for verification. After the verification is passed, it uses the private key to generate a standard token and returns it to the gateway;
## Configuration Examples
### Global Configuration for Authentication and Route-Level Authorization
Note: If a JWT matches multiple `jwks`, the first matching consumer will be applied according to the configuration order.
4. The gateway returns the response with the token to the client, and the client needs to cache this token locally;
5. The client sends a business request to the API gateway, carrying the token in the request;
6. The gateway uses the public key set by the user to verify the token in the request. After the verification is passed, the request is passed through to the backend service;
7. The backend service processes the business and responds;
8. The gateway returns the business response to the client.
In this entire process, the gateway uses the token authentication mechanism to realize the ability of users to use their own user system to authorize their API. Next, we will introduce the structured token JSON Web Token (JWT) used by the gateway to implement token authentication.
### 1.3 JWT
#### 1.3.1 Introduction
JSON Web Token (JWT) is an open standard RFC7519 based on JSON for executing a type of claim to pass between network applications. JWT can generally be used as an independent identity verification token, which can contain user identification, user roles, and permissions information, making it easier to obtain resources from the resource server, and can also add some other necessary declarative information for other business logic, especially suitable for the login scenario of distributed sites.
#### 1.3.2 Composition of JWT
`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ`
As shown in the example above, JWT is a string consisting of three parts:
- Header
- Payload
- Signature
**Header**
The header of the JWT carries two pieces of information:
- The type of the token, which is JWT
- The algorithm used for encryption
The gateway supports the following encryption algorithms:
```text
ES256, ES384, ES512,
HS256, HS384, HS512,
RS256, RS384, RS512,
PS256, PS384, PS512,
EdDSA
Configure the plugin at the instance level as follows:
```yaml
global_auth: false
consumers:
- name: consumer1
issuer: abcd
jwks: |
{
"keys": [
{
"kty": "oct",
"kid": "123",
"k": "hM0k3AbXBPpKOGg__Ql2Obcq7s60myWDpbHXzgKUQdYo7YCRp0gUqkCnbGSvZ2rGEl4YFkKqIqW7mTHdj-bcqXpNr-NOznEyMpVPOIlqG_NWVC3dydBgcsIZIdD-MR2AQceEaxriPA_VmiUCwfwL2Bhs6_i7eolXoY11EapLQtutz0BV6ZxQQ4dYUmct--7PLNb4BWJyQeWu0QfbIthnvhYllyl2dgeLTEJT58wzFz5HeNMNz8ohY5K0XaKAe5cepryqoXLhA-V-O1OjSG8lCNdKS09OY6O0fkyweKEtuDfien5tHHSsHXoAxYEHPFcSRL4bFPLZ0orTt1_4zpyfew",
"alg": "HS256"
}
]
}
- name: consumer2
issuer: abc
jwks: |
{
"keys": [
{
"kty": "RSA",
"e": "AQAB",
"use": "sig",
"kid": "123",
"alg": "RS256",
"n": "i0B67f1jggT9QJlZ_8QL9QQ56LfurrqDhpuu8BxtVcfxrYmaXaCtqTn7OfCuca7cGHdrJIjq99rz890NmYFZuvhaZ-LMt2iyiSb9LZJAeJmHf7ecguXS_-4x3hvbsrgUDi9tlg7xxbqGYcrco3anmalAFxsbswtu2PAXLtTnUo6aYwZsWA6ksq4FL3-anPNL5oZUgIp3HGyhhLTLdlQcC83jzxbguOim-0OEz-N4fniTYRivK7MlibHKrJfO3xa_6whBS07HW4Ydc37ZN3Rx9Ov3ZyV0idFblU519nUdqp_inXj1eEpynlxH60Ys_aTU2POGZh_25KXGdF_ZC_MSRw"
}
]
}
```
The complete header looks like the following JSON:
Configure the following for routes `route-a` and `route-b`:
```yaml
allow:
- consumer1
```
Configure the following for domain names `*.example.com` and `test.com`:
```yaml
allow:
- consumer2
```
**Explanation:**
The specified `route-a` and `route-b` refer to the routing names filled in when creating the gateway route. When these two routes are matched, the caller with the name consumer1 will be allowed access, while others will not be permitted.
The specified `*.example.com` and `test.com` are used to match the request domain names. When a matching domain name is found, the caller with the name consumer2 will be allowed access, while others will not.
Based on this configuration, the following requests will be allowed:
Suppose the following request matches the route-a.
**Setting the JWT in URL parameters**
```bash
curl 'http://xxx.hello.com/test?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMyJ9.eyJpc3MiOiJhYmNkIiwic3ViIjoidGVzdCIsImlhdCI6MTY2NTY2MDUyNywiZXhwIjoxODY1NjczODE5fQ.-vBSV0bKeDwQcuS6eeSZN9dLTUnSnZVk8eVCXdooCQ4'
```
**Setting the JWT in HTTP request headers**
```bash
curl http://xxx.hello.com/test -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMyJ9.eyJpc3MiOiJhYmNkIiwic3ViIjoidGVzdCIsImlhdCI6MTY2NTY2MDUyNywiZXhwIjoxODY1NjczODE5fQ.-vBSV0bKeDwQcuS6eeSZN9dLTUnSnZVk8eVCXdooCQ4'
```
After successful authentication and authorization, the request's header will include an `X-Mse-Consumer` field, in this example with the value `consumer1`, to identify the caller's name.
The following requests will be denied:
**Request without JWT returns 401**
```bash
curl http://xxx.hello.com/test
```
**Caller matching from the provided JWT has no access permission, returning 403**
```bash
# consumer1 is not in the allow list for *.example.com
curl 'http://xxx.example.com/test' -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMyJ9.eyJpc3MiOiJhYmNkIiwic3ViIjoidGVzdCIsImlhdCI6MTY2NTY2MDUyNywiZXhwIjoxODY1NjczODE5fQ.-vBSV0bKeDwQcuS6eeSZN9dLTUnSnZVk8eVCXdooCQ4'
```
#### Enable at Gateway Instance Level
The following configuration will enable JWT Auth authentication at the instance level, requiring all requests to be authenticated before accessing.
```yaml
global_auth: true
consumers:
- name: consumer1
issuer: abcd
jwks: |
{
"keys": [
{
"kty": "oct",
"kid": "123",
"k": "hM0k3AbXBPpKOGg__Ql2Obcq7s60myWDpbHXzgKUQdYo7YCRp0gUqkCnbGSvZ2rGEl4YFkKqIqW7mTHdj-bcqXpNr-NOznEyMpVPOIlqG_NWVC3dydBgcsIZIdD-MR2AQceEaxriPA_VmiUCwfwL2Bhs6_i7eolXoY11EapLQtutz0BV6ZxQQ4dYUmct--7PLNb4BWJyQeWu0QfbIthnvhYllyl2dgeLTEJT58wzFz5HeNMNz8ohY5K0XaKAe5cepryqoXLhA-V-O1OjSG8lCNdKS09OY6O0fkyweKEtuDfien5tHHSsHXoAxYEHPFcSRL4bFPLZ0orTt1_4zpyfew",
"alg": "HS256"
}
]
}
- name: consumer2
issuer: abc
jwks: |
{
"keys": [
{
"kty": "RSA",
"e": "AQAB",
"use": "sig",
"kid": "123",
"alg": "RS256",
"n": "i0B67f1jggT9QJlZ_8QL9QQ56LfurrqDhpuu8BxtVcfxrYmaXaCtqTn7OfCuca7cGHdrJIjq99rz890NmYFZuvhaZ-LMt2iyiSb9LZJAeJmHf7ecguXS_-4x3hvbsrgUDi9tlg7xxbqGYcrco3anmalAFxsbswtu2PAXLtTnUo6aYwZsWA6ksq4FL3-anPNL5oZUgIp3HGyhhLTLdlQcC83jzxbguOim-0OEz-N4fniTYRivK7MlibHKrJfO3xa_6whBS07HW4Ydc37ZN3Rx9Ov3ZyV0idFblU519nUdqp_inXj1eEpynlxH60Ys_aTU2POGZh_25KXGdF_ZC_MSRw"
}
]
}
```
## Common Error Codes
| HTTP Status Code | Error Message | Reason Description |
| ---------------- | ----------------------------- | ---------------------------------------------------------------------------- |
| 401 | Jwt missing | The request header did not provide a JWT |
| 401 | Jwt expired | The JWT has expired |
| 401 | Jwt verification fails | JWT payload verification failed, such as mismatched `iss` |
| 403 | Access Denied | No permission to access the current route |
## Detailed Description
### 1. Token-based Authentication
#### 1.1 Introduction
Many open APIs need to identify the requester's identity and determine whether the requested resource can be returned. A token is a mechanism used for identity verification. With this mechanism, applications do not need to retain user authentication information or session information on the server, allowing for stateless, distributed web application authorization, facilitating application scaling.
#### 1.2 Process Description
![](https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/2336348951/p135822.png)
The above image shows the entire business process sequence diagram for gateway authentication using JWT. Below, we will detail the steps indicated in the diagram:
1. The client initiates an authentication request to the API gateway, generally carrying the terminal user's username and password.
2. The gateway forwards the request directly to the backend service.
3. The backend service reads the verification information in the request (such as username and password) for validation. Upon successful verification, it generates a standard token using a private key and returns it to the gateway.
4. The gateway returns a response containing the token to the client, who must cache this token locally.
5. The client sends a business request to the API gateway, carrying the token in the request.
6. The gateway validates the token using the user's set public key. Upon successful validation, it forwards the request to the backend service.
7. The backend service processes the business and responds.
8. The gateway returns the business response to the client.
Throughout this process, the gateway utilizes the token authentication mechanism, enabling the user to authorize their API using their user system. Next, we will introduce the structured token used by the gateway for token authentication: JSON Web Token (JWT).
#### 1.3 JWT
##### 1.3.1 Introduction
JSON Web Token (JWT) is an open standard (RFC7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can be used as a stand-alone authentication token, capable of containing user identity, user roles, permissions, and other information, aiding in resource retrieval from resource servers and adding any additional claims required by business logic, particularly suitable for login scenarios for distributed sites.
##### 1.3.2 JWT Structure
`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ`
As shown above, JWT is a string composed of three parts:
- Header
- Payload
- Signature
**Header**
The header of the JWT carries two pieces of information:
- Token type, which is JWT
- Signing algorithm
The supported signing algorithms by the gateway are as follows:
```text
ES256, ES384, ES512,
HS256, HS384, HS512,
RS256, RS384, RS512,
PS256, PS384, PS512,
EdDSA
```
The complete header looks like the following JSON:
```js
{
'typ': 'JWT',
'alg': 'HS256'
}
```
The header is then Base64-encoded (this encoding can be symmetrically decoded), forming the first part:
`eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9`
**Payload**
The payload is where the actual information is stored. The details are defined below:
```
Then the header is Base64 encoded (this encoding is symmetrically decodable), forming the first part.
`eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9`
**Payload**
The payload is where valid information is stored. Its details are defined as follows:
```text
iss: The issuer of the token. This indicates who created the token and is a string value.
sub: The subject identifier. This is the unique identifier for the end user provided by the issuer, and is no longer than 255 ASCII characters, and is case-sensitive within the issuer's scope.
aud: The audience(s) of the token, which is an array of case-sensitive strings.
exp: The expiration time of the token, after which the token will be invalidated, is an integer declaration representing the Unix timestamp in seconds.
iat: The issuance time of the token, is an integer declaration representing the Unix timestamp in seconds.
jti: The unique identifier of the token, and the value is unique for every token created by the issuer. It is usually a cryptographically random value to prevent conflicts. This component adds a random entropy that an attacker cannot obtain to the structured token, making it more difficult for the token to be guessed or replayed.
```
Custom fields for a user feature can also be added, such as the example below adding a "name" field for the user's nickname:
iss: Token issuer. Indicates who created the token, this claim is a string.
sub: Subject Identifier, an identifier provided by the issuer for its end users, unique within the issuer's scope, up to 255 ASCII characters, case sensitive.
aud: Audience(s), the audience of the token, an array of strings that are case-sensitive.
exp: Expiration time, a timestamp of the token's expiration. Tokens expired beyond this time will be invalid. This claim is an integer, representing the number of seconds since January 1, 1970.
iat: Issuance time of the token, this claim is an integer, representing the number of seconds since January 1, 1970.
jti: Unique identifier for the token, the value of this claim must be unique for each token created by the token issuer to prevent collisions. It is typically a cryptographically random value. This value adds a random entropy component to the structured token that is not accessible to an attacker, helping prevent token guess and replay attacks.
```
Custom fields necessary for the user system can also be added, for example, the following example adds a nickname `name`:
```js
{
"sub": "1234567890",
"name": "John Doe"
}
```
The payload is then Base64-encoded, forming the second part of the JWT:
`JTdCJTBBJTIwJTIwJTIyc3ViJTIyJTNBJTIwJTIyMTIzNDU2Nzg5MCUyMiUyQyUwQSUyMCUyMCUyMm5hbWUlMjIlM0ElMjAlMjJKb2huJTIwRG9lJTIyJTBBJTdE`
**Signature**
This part is a string that consists of the Base64-encoded header and Base64-encoded payload concatenated with a period, followed by the encryption of the resulting string using the algorithm specified in the header (where $secret represents the user's private key).
```
Then encode it in Base64 to obtain the second part of the JWT:
`JTdCJTBBJTIwJTIwJTIyc3ViJTIyJTNBJTIwJTIyMTIzNDU2Nzg5MCUyMiUyQyUwQSUyMCUyMCUyMm5hbWUlMjIlM0ElMjAlMjJKb2huJTIwRG9lJTIyJTBBJTdE`
**Signature**
This part requires the Base64-encoded Header and Base64-encoded Payload to be connected by a period, and then encrypted using the signing method declared in the Header (where `$secret` represents the user's private key) to form the third part of the JWT.
```js
var encodedString = base64UrlEncode(header) + '.' + base64UrlEncode(payload);
var signature = HMACSHA256(encodedString, '$secret');
```
```
Connecting these three parts with a period creates a complete string that forms the JWT example at the beginning of section 1.3.2.
These three parts are then concatenated using periods to form the complete JWT string as shown in the example at the beginning of this section.
##### 1.3.3 Validity Period
The gateway will validate the `exp` field in the token. Once this field expires, the gateway will consider this token invalid and directly reject the request. The expiration time must be set.
#### 1.3.3 Time validity
##### 1.3.4 Characteristics of JWT
1. JWT is not encrypted by default; do not write secret data into JWT.
2. JWT can be used for both authentication and information exchange. Effectively using JWT can reduce the number of queries to the database on the server.
3. The biggest drawback of JWT is that since the server does not maintain session state, it cannot revoke a token during use or change the permissions of said token. In other words, once a JWT is issued, it will remain valid until expiration, unless the server implements additional logic.
4. JWT itself contains authentication information, and once leaked, anyone can gain all permissions of that token. To minimize theft, the validity period of JWT should be set to be relatively short. For some critical permissions, users should be re-authenticated.
5. To reduce theft, JWT should not be transmitted in plain text over HTTP but should use HTTPS for transmission.
The gateway will verify the exp field in the token. Once this field has expired, the gateway will consider the token invalid and reject the request directly. The expiration time value must be set.
#### 1.3.4 Several Characteristics of JWT
1. By default, JWT is not encrypted and cannot write secret data into JWT.
2. JWT can not only be used for authentication but also for exchanging information. Using JWT effectively can reduce the number of times servers query the database.
3. The biggest drawback of JWT is that the server cannot invalidate a token during use, or change the token's permission, because the server does not keep the session state. That is, once JWT is issued, it will always be valid before it expires, unless the server deploys additional logic.
4. JWT contains authentication information itself. Once leaked, anyone can obtain all permissions of the token. To reduce theft, the expiration time of JWT should be set relatively short. For some more important permissions, users should be authenticated again when using them.
5. To reduce theft, JWT should not be transmitted in plaintext using the HTTP protocol, and the HTTPS protocol should be used for transmission.
## 2. How to apply the JWT plugin to protect the API of the user system
### 2.1 Generate a pair of JWK (JSON Web Key)
**Method 1: Generate online**
Users can generate the private and public keys used for token generation and verification on this website https://mkjwk.org. The private key is used for the authorization service to issue JWT, and the public key is configured into the JWT plugin for the gateway to verify the signature of the request. Note that the JWKs format configuration used by the gateway requires the public key in the figure below to be placed in the keys structure, such as: `{"keys":[{"kty":"RSA","e":"AQAB",...}]}`
<img src="https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/2336348951/p135823.png" style="zoom:50%" />
**Method 2: Generate locally**
This article uses a Java example to illustrate, and users of other languages can also find relevant tools to generate key pairs. Create a new Maven project and add the following dependencies:
### 2. How User Systems Apply the JWT Plugin to Protect APIs
#### 2.1 Generating a Pair of JWKs (JSON Web Keys)
**Method 1: Online Generation:**
Users can generate the private and public keys used for token generation and verification at this site https://mkjwk.org. The private key is used by the authorization service to issue JWTs, and the public key is configured into the JWT plugin for the gateway to verify requests. Pay attention to the jwks format configuration used by the gateway. In the image below, the Public Key should be placed into the keys structure, for example: `{"keys":[{"kty":"RSA","e":"AQAB",...}]}`
<img src="https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/2336348951/p135823.png" style="zoom:50%" />
**Method 2: Local Generation:**
This article demonstrates using Java; users of other languages can find related tools to generate key pairs. Create a new Maven project and include the following dependency:
```xml
<dependency>
<groupId>org.bitbucket.b_c</groupId>
<artifactId>jose4j</artifactId>
<version>0.7.0</version>
</dependency>
```
Use the following code to generate a pair of RSA keys:
```
Use the following code to generate a pair of RSA keys:
```java
RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
final String publicKeyString = rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY);
final String privateKeyString = rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);
```
### 2.2 Implement the token issuance authentication service using the private key in JWK
The Keypair JSON string generated online in Section 2.1 (the first of the three boxes) or privateKeyString JSON string generated locally needs to be used as the private key to issue tokens for trusted users to access protected APIs. The specific implementation can refer to the following example. The form of issuing tokens to customers is determined by the user according to the specific business scenario. The function of issuing tokens can be deployed in the production environment and configured as a normal API for visitors to obtain through username and password, or tokens can be generated directly in the local environment and copied to designated users for use.
```
#### 2.2 Using the Private Key in JWK to Implement the Token Issuance Authentication Service
You will need to use the Keypair JSON string (the first inside the three boxes) generated online in section 2.1 or the locally generated privateKeyString JSON string as the private key to issue tokens for authorizing trusted users to access protected APIs. The specific implementation can refer to the example below. The form of issuing tokens to customers can be determined by the user based on the specific business scenario; it can be deployed in the production environment, configured to be a normal API that visitors can access through username and password, or tokens can be generated locally and directly copied for specified users to use.
```java
import java.security.PrivateKey;
import java.security.PrivateKey;
import org.jose4j.json.JsonUtil;
import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.jwk.RsaJwkGenerator;
@@ -173,32 +309,29 @@ import org.jose4j.jws.JsonWebSignature;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.NumericDate;
import org.jose4j.lang.JoseException;
public class GenerateJwtDemo {
public static void main(String[] args) throws JoseException {
String keyId = "uniq_key";
//Use the Keypair generated in section 2.1 of this article
// Use the Keypair generated in section 2.1
String privateKeyJson = "{\n"
+ " \"kty\": \"RSA\",\n"
+ " \"d\": "
+
"\"O9MJSOgcjjiVMNJ4jmBAh0mRHF_TlaVva70Imghtlgwxl8BLfcf1S8ueN1PD7xV6Cnq8YenSKsfiNOhC6yZ_fjW1syn5raWfj68eR7cjHWjLOvKjwVY33GBPNOvspNhVAFzeqfWneRTBbga53Agb6jjN0SUcZdJgnelzz5JNdOGaLzhacjH6YPJKpbuzCQYPkWtoZHDqWTzCSb4mJ3n0NRTsWy7Pm8LwG_Fd3pACl7JIY38IanPQDLoighFfo-Lriv5z3IdlhwbPnx0tk9sBwQBTRdZ8JkqqYkxUiB06phwr7mAnKEpQJ6HvhZBQ1cCnYZ_nIlrX9-I7qomrlE1UoQ\",\n"
+ " \"d\": \"O9MJSOgcjjiVMNJ4jmBAh0mRHF_TlaVva70Imghtlgwxl8BLfcf1S8ueN1PD7xV6Cnq8YenSKsfiNOhC6yZ_fjW1syn5raWfj68eR7cjHWjLOvKjwVY33GBPNOvspNhVAFzeqfWneRTBbga53Agb6jjN0SUcZdJgnelzz5JNdOGaLzhacjH6YPJKpbuzCQYPkWtoZHDqWTzCSb4mJ3n0NRTsWy7Pm8LwG_Fd3pACl7JIY38IanPQDLoighFfo-Lriv5z3IdlhwbPnx0tk9sBwQBTRdZ8JkqqYkxUiB06phwr7mAnKEpQJ6HvhZBQ1cCnYZ_nIlrX9-I7qomrlE1UoQ\",\n"
+ " \"e\": \"AQAB\",\n"
+ " \"alg\": \"RS256\",\n"
+ " \"n\": \"vCuB8MgwPZfziMSytEbBoOEwxsG7XI3MaVMoocziP4SjzU4IuWuE_DodbOHQwb_thUru57_Efe"
+
"--sfATHEa0Odv5ny3QbByqsvjyeHk6ZE4mSAV9BsHYa6GWAgEZtnDceeeDc0y76utXK2XHhC1Pysi2KG8KAzqDa099Yh7s31AyoueoMnrYTmWfEyDsQL_OAIiwgXakkS5U8QyXmWicCwXntDzkIMh8MjfPskesyli0XQD1AmCXVV3h2Opm1Amx0ggSOOiINUR5YRD6mKo49_cN-nrJWjtwSouqDdxHYP-4c7epuTcdS6kQHiQERBd1ejdpAxV4c0t0FHF7MOy9kw\"\n"
+ " \"n\": \"vCuB8MgwPZfziMSytEbBoOEwxsG7XI3MaVMoocziP4SjzU4IuWuE_DodbOHQwb_thUru57_Efe--sfATHEa0Odv5ny3QbByqsvjyeHk6ZE4mSAV9BsHYa6GWAgEZtnDceeeDc0y76utXK2XHhC1Pysi2KG8KAzqDa099Yh7s31AyoueoMnrYTmWfEyDsQL_OAIiwgXakkS5U8QyXmWicCwXntDzkIMh8MjfPskesyli0XQD1AmCXVV3h2Opm1Amx0ggSOOiINUR5YRD6mKo49_cN-nrJWjtwSouqDdxHYP-4c7epuTcdS6kQHiQERBd1ejdpAxV4c0t0FHF7MOy9kw\"\n"
+ "}";
JwtClaims claims = new JwtClaims();
claims.setGeneratedJwtId();
claims.setIssuedAtToNow();
//Expiration time must be set
// Expiration time must be set
NumericDate date = NumericDate.now();
date.addSeconds(120*60);
claims.setExpirationTime(date);
claims.setNotBeforeMinutesInThePast(1);
claims.setSubject("YOUR_SUBJECT");
claims.setAudience("YOUR_AUDIENCE");
//Add custom parameters, use String type for all values
// Add custom parameters, all values should be String type
claims.setClaim("userId", "1213234");
claims.setClaim("email", "userEmail@youapp.com");
JsonWebSignature jws = new JsonWebSignature();
@@ -206,194 +339,9 @@ public class GenerateJwtDemo {
jws.setKeyIdHeaderValue(keyId);
jws.setPayload(claims.toJson());
PrivateKey privateKey = new RsaJsonWebKey(JsonUtil.parseJson(privateKeyJson)).getPrivateKey();
jws.setKey(privateKey);
String jwtResult = jws.getCompactSerialization();
System.out.println("Generate Json Web token , result is " + jwtResult);
}
}
```
# Plugin Configuration Guide
## Configuration Fields
| Name | Data Type | Required | Default | Description |
| ----------- | --------------- | ------------------------------------------- | ------ | ----------------------------------------------------------- |
| `consumers` | array of object | Yes | - | Configures callers of the service for authenticating requests |
| `_rules_` | array of object | Optional | - | Configures access control lists for specific routes or domains for authorizing requests |
The configuration field descriptions for each item in consumers are as follows:
| Name | Data Type | Required | Default | Description|
| ----------------------- | ----------------- | -------- | ------------------------------------------------- | ------------------------ |
| `name` | string | Yes | - | Configures the name of this consumer |
| `jwks` | string | Yes | - | Specifies a JSON Web Key Set, as defined in https://www.rfc-editor.org/rfc/rfc7517, consisting of public keys (or symmetric keys) used to verify the signature of JWT |
| `issuer` | string | Yes | - | The issuer of the JWT, which should be consistent with the iss field in the payload |
| `claims_to_headers` | array of object | Optional | - | Extracts the specified fields from the JWT's payload and sets them to the specified request headers for forwarding to the backend |
| `from_headers` | array of object | Optional | {"name":"Authorization","value_prefix":"Bearer "} | Extracts the JWT from the specified request headers |
| `from_params` | array of string | Optional | access_token | Extracts the JWT from the specified URL parameters |
| `from_cookies` | array of string | Optional | - | Extracts the JWT from the specified cookie(s) |
| `clock_skew_seconds` | number | Optional | 60 | The amount of clock skew, in seconds, that is allowed when verifying the exp and iat fields of the JWT |
| `keep_token` | bool | Optional | ture | Whether to keep the JWT when forwarding it to the backend |
**Note:**
- The default value is used only if neither `from_headers`, `from_params`, nor `from_cookies` are configured.
The configuration field descriptions for each item in `from_headers` are as follows:
| Name | Data Type | Required| Default | Description |
| ---------------- | --------------- | ------- | ------ | --------------------------------------------------------- |
| `name` | string | Yes | - | Specifies the request header to extract the JWT from |
| `value_prefix` | string | Yes | - | Removes the specified prefix from the request header's value, leaving the rest as the JWT |
The configuration field descriptions for each item in `claims_to_headers` are as follows:
| Name | Data Type | Required| Default | Description |
| ---------------- | --------------- | ------- | ------ | --------------------------------------------------------- |
| `claim` | string | Yes | - | The name of the field in the JWT payload, which must be a string or unsigned integer |
| `header` | string | Yes | - | Sets the value of the specified request header to the value of the specified field in the payload, for forwarding to the backend |
| `override` | bool | Optional | true | If true, overrides an existing header with the same name; if false, appends the header to the existing headers |
The configuration field descriptions for each item in `_rules_` are as follows:
| Name | Data Type | Required| Default | Description |
| ---------------- | --------------- | ------------------------------------------------- | ------ | -------------------------------------------------- |
| `_match_route_` | array of string | Optional, select either `_match_route_` or `_match_domain_` | - | Configures the route names to match|
| `_match_domain_` | array of string | Optional, select either `_match_route_` or `_match_domain_` | - | Configures the domains to match |
| `allow` | array of string | Required | - | Configures the consumer names allowed to access the matched requests |
**Note:**
- If the `_rules_` field is not configured, authentication and authorization are enabled for all routes of the current gateway instance by default;
- For authenticated and authorized requests, a `X-Mse-Consumer` field is added to the request header to identify the caller's name.
## Configuration Example
### Enable for Specific Routes or Domains
The following configuration enables Jwt Auth authentication and authorization for specific routes or domains of the gateway. If a JWT can match multiple `jwks`, the first matching `consumer` is hit according to the configuration order.
```yaml
consumers:
- name: consumer1
issuer: abcd
jwks: |
{
"keys": [
{
"kty": "oct",
"kid": "123",
"k": "hM0k3AbXBPpKOGg__Ql2Obcq7s60myWDpbHXzgKUQdYo7YCRp0gUqkCnbGSvZ2rGEl4YFkKqIqW7mTHdj-bcqXpNr-NOznEyMpVPOIlqG_NWVC3dydBgcsIZIdD-MR2AQceEaxriPA_VmiUCwfwL2Bhs6_i7eolXoY11EapLQtutz0BV6ZxQQ4dYUmct--7PLNb4BWJyQeWu0QfbIthnvhYllyl2dgeLTEJT58wzFz5HeNMNz8ohY5K0XaKAe5cepryqoXLhA-V-O1OjSG8lCNdKS09OY6O0fkyweKEtuDfien5tHHSsHXoAxYEHPFcSRL4bFPLZ0orTt1_4zpyfew",
"alg": "HS256"
}
]
}
- name: consumer2
issuer: abc
jwks: |
{
"keys": [
{
"kty": "RSA",
"e": "AQAB",
"use": "sig",
"kid": "123",
"alg": "RS256",
"n": "i0B67f1jggT9QJlZ_8QL9QQ56LfurrqDhpuu8BxtVcfxrYmaXaCtqTn7OfCuca7cGHdrJIjq99rz890NmYFZuvhaZ-LMt2iyiSb9LZJAeJmHf7ecguXS_-4x3hvbsrgUDi9tlg7xxbqGYcrco3anmalAFxsbswtu2PAXLtTnUo6aYwZsWA6ksq4FL3-anPNL5oZUgIp3HGyhhLTLdlQcC83jzxbguOim-0OEz-N4fniTYRivK7MlibHKrJfO3xa_6whBS07HW4Ydc37ZN3Rx9Ov3ZyV0idFblU519nUdqp_inXj1eEpynlxH60Ys_aTU2POGZh_25KXGdF_ZC_MSRw"
}
]
}
# Use the _rules_ field for fine-grained rule configuration
_rules_:
# Rule 1: Effective when matched by route name
- _match_route_:
- route-a
- route-b
allow:
- consumer1
# Rule 2: Effective when matched by domain name
- _match_domain_:
- "*.example.com"
- test.com
allow:
- consumer2
```
In this example, the `route-a` and `route-b` specified in `_match_route_` are the names of the routes filled in when creating the gateway route. When these two routes are matched, access will be allowed for the caller with the `name` of `consumer1`, and other callers will not be allowed to access.
The `*.example.com` and `test.com` specified in `_match_domain_` are used to match the domain names of the requests. When a domain name match is found, access will be allowed for the caller with the `name` of `consumer2`, and other callers will not be allowed to access.
#### According to this configuration, the following requests are allowed:
Assuming the following requests will match the route-a route:
**JWT is set in URL parameter**
```bash
curl 'http://xxx.hello.com/test?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMyJ9.eyJpc3MiOiJhYmNkIiwic3ViIjoidGVzdCIsImlhdCI6MTY2NTY2MDUyNywiZXhwIjoxODY1NjczODE5fQ.-vBSV0bKeDwQcuS6eeSZN9dLTUnSnZVk8eVCXdooCQ4'
```
**JWT is set in HTTP request header**
```bash
curl http://xxx.hello.com/test -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMyJ9.eyJpc3MiOiJhYmNkIiwic3ViIjoidGVzdCIsImlhdCI6MTY2NTY2MDUyNywiZXhwIjoxODY1NjczODE5fQ.-vBSV0bKeDwQcuS6eeSZN9dLTUnSnZVk8eVCXdooCQ4'
```
After authentication and authorization, a `X-Mse-Consumer` field will be added in the request header with a value of `consumer1` in this example, to identify the name of the caller.
#### The following requests will be denied:
**Request without JWT provided, returns 401**
```bash
curl http://xxx.hello.com/test
```
**The consumer matched by the provided JWT in the request does not have access, returns 403**
```bash
# consumer1 is not in the allow list of *.example.com
curl 'http://xxx.example.com/test' -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMyJ9.eyJpc3MiOiJhYmNkIiwic3ViIjoidGVzdCIsImlhdCI6MTY2NTY2MDUyNywiZXhwIjoxODY1NjczODE5fQ.-vBSV0bKeDwQcuS6eeSZN9dLTUnSnZVk8eVCXdooCQ4'
```
### Enabling at Gateway Instance Level
The following configuration does not specify the `_rules_` field, so JWT authentication will be enabled at the gateway instance level:
```yaml
consumers:
- name: consumer1
issuer: abcd
jwks: |
{
"keys": [
{
"kty": "oct",
"kid": "123",
"k": "hM0k3AbXBPpKOGg__Ql2Obcq7s60myWDpbHXzgKUQdYo7YCRp0gUqkCnbGSvZ2rGEl4YFkKqIqW7mTHdj-bcqXpNr-NOznEyMpVPOIlqG_NWVC3dydBgcsIZIdD-MR2AQceEaxriPA_VmiUCwfwL2Bhs6_i7eolXoY11EapLQtutz0BV6ZxQQ4dYUmct--7PLNb4BWJyQeWu0QfbIthnvhYllyl2dgeLTEJT58wzFz5HeNMNz8ohY5K0XaKAe5cepryqoXLhA-V-O1OjSG8lCNdKS09OY6O0fkyweKEtuDfien5tHHSsHXoAxYEHPFcSRL4bFPLZ0orTt1_4zpyfew",
"alg": "HS256"
}
]
}
- name: consumer2
issuer: abc
jwks: |
{
"keys": [
{
"kty": "RSA",
"e": "AQAB",
"use": "sig",
"kid": "123",
"alg": "RS256",
"n": "i0B67f1jggT9QJlZ_8QL9QQ56LfurrqDhpuu8BxtVcfxrYmaXaCtqTn7OfCuca7cGHdrJIjq99rz890NmYFZuvhaZ-LMt2iyiSb9LZJAeJmHf7ecguXS_-4x3hvbsrgUDi9tlg7xxbqGYcrco3anmalAFxsbswtu2PAXLtTnUo6aYwZsWA6ksq4FL3-anPNL5oZUgIp3HGyhhLTLdlQcC83jzxbguOim-0OEz-N4fniTYRivK7MlibHKrJfO3xa_6whBS07HW4Ydc37ZN3Rx9Ov3ZyV0idFblU519nUdqp_inXj1eEpynlxH60Ys_aTU2POGZh_25KXGdF_ZC_MSRw"
}
]
}
```
# Common Error Codes
| HTTP Status Code | Error Message | Reason Description|
|------------------| ---------------------- | -------------------------------------------------------------------------------- |
| 401 | JWT missing | The JWT is not provided in the request header. |
| 401 | JWT expired | The JWT has expired. |
| 401 | JWT verification fails | The JWT payload verification failed, such as the iss mismatch. |
| 403 | Access denied | Access to the current route is denied. |

View File

@@ -1,15 +1,32 @@
# 功能说明
---
title: Key 认证
keywords: [higress,key auth]
description: Key 认证插件配置参考
---
## 功能说明
`key-auth`插件实现了基于 API Key 进行认证鉴权的功能,支持从 HTTP 请求的 URL 参数或者请求头解析 API Key同时验证该 API Key 是否有权限访问。
# 配置字段
## 运行属性
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------- | --------------- | ------------------------------------------- | ------ | ----------------------------------------------------------- |
| `consumers` | array of object | 必填 | - | 配置服务的调用者,用于对请求进行认证 |
| `keys` | array of string | 必填 | - | API Key 的来源字段名称,可以是 URL 参数或者 HTTP 请求头名称 |
| `in_query` | bool | `in_query``in_header` 至少有一个为 true | true | 配置 true 时,网关会尝试从 URL 参数中解析 API Key |
| `in_header` | bool | `in_query``in_header` 至少有一个为 true | true | 配置 true 时,网关会尝试从 HTTP 请求头中解析 API Key |
| `_rules_` | array of object | 选填 | - | 配置特定路由或域名的访问权限列表,用于对请求进行鉴权 |
插件执行阶段:`认证阶段`
插件执行优先级:`310`
## 配置字段
**注意:**
- 在一个规则里,鉴权配置和认证配置不可同时存在
- 对于通过认证鉴权的请求请求的header会被添加一个`X-Mse-Consumer`字段,用以标识调用者的名称。
### 认证配置
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------- | --------------- | ------------------------------------------- | ------ | ----------------------------------------------------------- |
| `global_auth` | bool | 选填(**仅实例级别配置** | - | 只能在实例级别配置若配置为true则全局生效认证机制; 若配置为false则只对做了配置的域名和路由生效认证机制若不配置则仅当没有域名和路由配置时全局生效兼容老用户使用习惯。 |
| `consumers` | array of object | 必填 | - | 配置服务的调用者,用于对请求进行认证 |
| `keys` | array of string | 必填 | - | API Key 的来源字段名称,可以是 URL 参数或者 HTTP 请求头名称 |
| `in_query` | bool | `in_query``in_header` 至少有一个为 true | true | 配置 true 时,网关会尝试从 URL 参数中解析 API Key |
| `in_header` | bool | `in_query``in_header` 至少有一个为 true | true | 配置 true 时,网关会尝试从 HTTP 请求头中解析 API Key |
`consumers`中每一项的配置字段说明如下:
@@ -18,25 +35,22 @@
| `credential` | string | 必填 | - | 配置该consumer的访问凭证 |
| `name` | string | 必填 | - | 配置该consumer的名称 |
`_rules_` 中每一项的配置字段说明如下:
### 鉴权配置(非必需)
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ---------------- | --------------- | ------------------------------------------------- | ------ | -------------------------------------------------- |
| `_match_route_` | array of string | 选填`_match_route_``_match_domain_`中选填一项 | - | 配置要匹配的路由名称 |
| `_match_domain_` | array of string | 选填,`_match_route_``_match_domain_`中选填一项 | - | 配置要匹配的域名 |
| `allow` | array of string | 必填 | - | 对于符合匹配条件的请求配置允许访问的consumer名称 |
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------- | --------------- | ------------------------------------------- | ------ | ----------------------------------------------------------- |
| `allow` | array of string | 选填(**非实例级别配置**) | - | 只能在路由或域名等细粒度规则上配置,对于符合匹配条件的请求,配置允许访问的 consumer从而实现细粒度的权限控制 |
**注意:**
- 若不配置`_rules_`字段,则默认对当前网关实例的所有路由开启认证;
- 对于通过认证鉴权的请求请求的header会被添加一个`X-Mse-Consumer`字段,用以标识调用者的名称。
## 配置示例
# 配置示例
### 全局配置认证和路由粒度进行鉴权
## 对特定路由或域名开启
以下配置将对网关特定路由或域名开启Key Auth认证和鉴权。credential字段不能重复。
以下配置将对网关特定路由或域名开启 Key Auth 认证和鉴权,注意`credential`字段不能重复
在实例级别做如下插件配置:
```yaml
global_auth: false
consumers:
- credential: 2bda943c-ba2b-11ec-ba07-00163e1250b5
name: consumer1
@@ -44,31 +58,33 @@ consumers:
name: consumer2
keys:
- apikey
in_query: true
# 使用 _rules_ 字段进行细粒度规则配置
_rules_:
# 规则一:按路由名称匹配生效
- _match_route_:
- route-a
- route-b
allow:
- consumer1
# 规则二:按域名匹配生效
- _match_domain_:
- "*.example.com"
- test.com
allow:
- consumer2
- x-api-key
```
此例 `_match_route_` 中指定的 `route-a``route-b` 即在创建网关路由时填写的路由名称,当匹配到这两个路由时,将允许`name``consumer1`的调用者访问,其他调用者不允许访问;
route-a 和 route-b 这两个路由做如下配置:
此例 `_match_domain_` 中指定的 `*.example.com``test.com` 用于匹配请求的域名,当发现域名匹配时,将允许`name``consumer2`的调用者访问,其他调用者不允许访问。
```yaml
allow:
- consumer1
```
### 根据该配置,下列请求可以允许访问:
对 *.example.com 和 test.com 在这两个域名做如下配置:
```yaml
allow:
- consumer2
```
**说明:**
此例指定的route-a和route-b即在创建网关路由时填写的路由名称当匹配到这两个路由时将允许name为consumer1的调用者访问其他调用者不允许访问。
此例指定的*.example.com和test.com用于匹配请求的域名当发现域名匹配时将允许name为consumer2的调用者访问其他调用者不被允许访问。
根据该配置,下列请求可以允许访问:
假设以下请求会匹配到route-a这条路由
n
**将 API Key 设置在 url 参数中**
```bash
curl http://xxx.hello.com/test?apikey=2bda943c-ba2b-11ec-ba07-00163e1250b5
@@ -80,7 +96,7 @@ curl http://xxx.hello.com/test -H 'x-api-key: 2bda943c-ba2b-11ec-ba07-00163e125
认证鉴权通过后请求的header中会被添加一个`X-Mse-Consumer`字段,在此例中其值为`consumer1`,用以标识调用方的名称
### 下列请求将拒绝访问:
下列请求将拒绝访问:
**请求未提供 API Key返回401**
```bash
@@ -97,11 +113,12 @@ curl http://xxx.hello.com/test?apikey=926d90ac-ba2e-11ec-ab68-00163e1250b5
curl http://xxx.hello.com/test?apikey=c8c8e9ca-558e-4a2d-bb62-e700dcc40e35
```
## 网关实例级别开启
### 网关实例级别开启
以下配置未指定`_rules_`字段,因此将对网关实例级别开启 Key Auth 认证
以下配置将对网关实例级别开启 Basic Auth 认证,所有请求均需要经过认证后才能访问。
```yaml
global_auth: true
consumers:
- credential: 2bda943c-ba2b-11ec-ba07-00163e1250b5
name: consumer1
@@ -109,13 +126,15 @@ consumers:
name: consumer2
keys:
- apikey
in_query: true
- x-api-key
```
# 相关错误码
## 相关错误码
| HTTP 状态码 | 出错信息 | 原因说明 |
| ----------- | --------------------------------------------------------- | ----------------------- |
| 401 | No API key found in request | 请求提供 API Key |
| 401 | Request denied by Key Auth check. Muti API key found in request | 请求提供多个 API Key |
| 401 | Request denied by Key Auth check. No API key found in request | 请求未提供 API Key |
| 401 | Request denied by Key Auth check. Invalid API key | 不允许当前 API Key 访问 |
| 403 | Request denied by Basic Auth check. Unauthorized consumer | 请求的调用方无访问权限 |
| 403 | Request denied by Key Auth check. Unauthorized consumer | 请求的调用方无访问权限 |

View File

@@ -1,43 +1,47 @@
# Features
The `key-auth` plug-in implements the authentication function based on the API Key, supports parsing the API Key from the URL parameter or request header of the HTTP request, and verifies whether the API Key has permission to access.
---
title: Key Authentication
keywords: [higress,key auth]
description: Key Authentication Plugin Configuration Reference
---
## Function Description
The `key-auth` plugin implements authentication based on API Key, supporting the parsing of the API Key from HTTP request URL parameters or request headers, while also verifying whether the API Key has permission to access the resource.
# Configuration field
## Runtime Properties
Plugin Execution Phase: `Authentication Phase`
Plugin Execution Priority: `310`
| Name | Data Type | Parameter requirements | Default| Description |
| ----------- | --------------- | -------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------- |
| `consumers` | array of object | Required | - | Configure the caller of the service to authenticate the request. |
| `keys` | array of string | Required | - | The name of the source field of the API Key, which can be a URL parameter or an HTTP request header name. |
| `in_query` | bool | At least one of `in_query` and `in_header` must be true. | true | When configured true, the gateway will try to parse the API Key from the URL parameters. |
| `in_header` | bool | The same as above. | true | The same as above. |
| `_rules_` | array of object | Optional | - | Configure the access list of a specific route or domain name for authenticating requests. |
## Configuration Fields
**Note:**
- Authentication and authorization configurations cannot coexist within a single rule.
- For requests that are authenticated, a header field `X-Mse-Consumer` will be added to identify the caller's name.
### Authentication Configuration
| Name | Data Type | Requirements | Default Value | Description |
| ------------- | ---------------- | ----------------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `global_auth` | bool | Optional (**Instance-Level Configuration Only**) | - | Can only be configured at the instance level; if set to true, the authentication mechanism takes effect globally; if set to false, it only applies to the configured hostnames and routes. If not configured, it will only take effect globally when no hostname and route configurations are present (to maintain compatibility with older user habits). |
| `consumers` | array of object | Required | - | Configures the service callers for request authentication. |
| `keys` | array of string | Required | - | Source field names for the API Key, which can be URL parameters or HTTP request header names. |
| `in_query` | bool | At least one of `in_query` and `in_header` must be true | true | When configured as true, the gateway will attempt to parse the API Key from URL parameters. |
| `in_header` | bool | At least one of `in_query` and `in_header` must be true | true | When configured as true, the gateway will attempt to parse the API Key from HTTP request headers. |
The configuration fields of each item in `consumers` are described as follows:
The configuration field descriptions for each item in `consumers` are as follows:
| Name | Data Type | Requirements | Default Value | Description |
| ------------ | --------- | ------------ | ------------- | ------------------------------ |
| `credential` | string | Required | - | Configures the access credential for this consumer. |
| `name` | string | Required | - | Configures the name for this consumer. |
| Name | Data Type | Parameter requirements | Default | Description |
| ------------ | --------- | -----------------------| ------ | ------------------------------------------- |
| `credential` | string | Required | - | Configure the consumer's access credentials. |
| `name` | string | Required | - | Configure the name of the consumer. |
### Authorization Configuration (Optional)
| Name | Data Type | Requirements | Default Value | Description |
| ----------- | ---------------- | ----------------------------------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `allow` | array of string | Optional (**Non-Instance Level Configuration**) | - | Can only be configured on fine-grained rules such as routes or hostnames; specifies the allowed consumers for matching requests, allowing for fine-grained permission control. |
The configuration fields of each item in `_rules_` are described as follows:
| Name | Data Type | Parameter requirements | Default| Description |
| ---------------- | --------------- | --------------------------------------------------------------------- | ------ | -------------------------------------------------- |
| `_match_route_` | array of string | OptionalOptionally fill in one of `_match_route_`, `_match_domain_`. | - | Configure the route name to match. |
| `_match_domain_` | array of string | OptionalOptionally fill in one of `_match_route_`, `_match_domain_`. | - | Configure the domain name to match. |
| `allow` | array of string | Required | - | For requests that meet the matching conditions, configure the name of the consumer that is allowed to access. |
**Warning**
- If the `_rules_` field is not configured, authentication will be enabled for all routes of the current gateway instance by default;
- For a request that passes authentication, an `X-Mse-Consumer` field will be added to the request header to identify the name of the caller.
# Example configuration
## Enabled for specific routes or domains
The following configuration will enable Key Auth authentication and authentication for gateway-specific routes or domain names. Note that the `credential` field can not be repeated.
## Configuration Example
### Global Configuration for Authentication and Granular Route Authorization
The following configuration will enable Key Auth authentication and authorization for specific routes or hostnames in the gateway. The `credential` field must not repeat.
At the instance level, do the following plugin configuration:
```yaml
global_auth: false
consumers:
- credential: 2bda943c-ba2b-11ec-ba07-00163e1250b5
name: consumer1
@@ -45,64 +49,63 @@ consumers:
name: consumer2
keys:
- apikey
in_query: true
# Use the _rules_ field for fine-grained rule configuration
_rules_:
# Rule 1: Match by route name to take effect
- _match_route_:
- route-a
- route-b
allow:
- consumer1
# Rule 2: Take effect by domain name matching
- _match_domain_:
- "*.example.com"
- test.com
allow:
- consumer2
- x-api-key
```
The `route-a` and `route-b` specified in `_match_route_` in this example are the route names filled in when creating the gateway route. When these two routes are matched, calls whose `name` is `consumer1` will be allowed Access by callers, other callers are not allowed to access;
For routes route-a and route-b, do the following configuration:
```yaml
allow:
- consumer1
```
`*.example.com` and `test.com` specified in `_match_domain_` in this example are used to match the domain name of the request. When the domain name matches, the caller whose `name` is `consumer2` will be allowed to access, and other calls access is not allowed.
For the hostnames *.example.com and test.com, do the following configuration:
```yaml
allow:
- consumer2
```
### Depending on this configuration, the following requests would allow access
**Note:**
The routes route-a and route-b specified in this example refer to the route names filled in when creating the gateway routes. When matched with these two routes, requests from the caller named consumer1 will be allowed while others will be denied.
Assume that the following request will match the route-a route:
The specified hostnames *.example.com and test.com are used to match the request's domain name. When a domain name is matched, callers named consumer2 will be allowed while others will be denied.
**Set the API Key in the url parameter**
Based on this configuration, the following requests will be allowed:
Assuming the following request matches route-a:
**Setting API Key in URL Parameters**
```bash
curl http://xxx.hello.com/test?apikey=2bda943c-ba2b-11ec-ba07-00163e1250b5
```
**Set the API Key in the http request header**
**Setting API Key in HTTP Request Headers**
```bash
curl http://xxx.hello.com/test -H 'x-api-key: 2bda943c-ba2b-11ec-ba07-00163e1250b5'
```
After the authentication is passed, an `X-Mse-Consumer` field will be added to the header of the request. In this example, its value is `consumer1`, which is used to identify the name of the caller.
After successful authentication and authorization, the request's header will have an added `X-Mse-Consumer` field with the value `consumer1`, to identify the name of the caller.
### The following requests will deny access
**The request does not provide an API Key, return 401**
The following requests will be denied access:
**Request without an API Key returns 401**
```bash
curl http://xxx.hello.com/test
```
**The API Key provided by the request is not authorized to access, return 401**
**Request with an invalid API Key returns 401**
```bash
curl http://xxx.hello.com/test?apikey=926d90ac-ba2e-11ec-ab68-00163e1250b5
```
**The caller matched according to the API Key provided in the request has no access rights, return 403**
**Caller matched with provided API Key has no access rights, returns 403**
```bash
# consumer2 is not in the allow list of route-a
curl http://xxx.hello.com/test?apikey=c8c8e9ca-558e-4a2d-bb62-e700dcc40e35
```
## Gateway instance level enabled
The following configuration does not specify the `_rules_` field, so Key Auth authentication will be enabled at the gateway instance level.
### Enabling at the Instance Level
The following configuration will enable Basic Auth authentication at the instance level for the gateway, requiring all requests to pass authentication before accessing.
```yaml
global_auth: true
consumers:
- credential: 2bda943c-ba2b-11ec-ba07-00163e1250b5
name: consumer1
@@ -110,14 +113,13 @@ consumers:
name: consumer2
keys:
- apikey
in_query: true
- x-api-key
```
# Error code
| HTTP status code | Error information | Reason |
| ---------------- | --------------------------------------------------------- | -------------------------------------------- |
| 401 | No API key found in request. | API not provided by request Key. |
| 401 | Request denied by Key Auth check. Invalid API key. | Current API Key access is not allowed. |
| 403 | Request denied by Basic Auth check. Unauthorized consumer. | The requested caller does not have access. |
## Related Error Codes
| HTTP Status Code | Error Message | Reason Explanation |
| ---------------- | ---------------------------------------------------------- | --------------------------------- |
| 401 | Request denied by Key Auth check. Multiple API keys found in request | Multiple API Keys provided in the request. |
| 401 | Request denied by Key Auth check. No API key found in request | API Key not provided in the request. |
| 401 | Request denied by Key Auth check. Invalid API key | The current API Key is not authorized for access. |
| 403 | Request denied by Key Auth check. Unauthorized consumer | The caller does not have access permissions. |

View File

@@ -1,11 +1,18 @@
<p>
<a href="README_EN.md"> English </a> | 中文
</p>
---
title: 基于 Key 的本地限流
keywords: [higress,key rate limit]
description: Key 本地限流插件配置参考
---
# 功能说明
## 功能说明
`key-rate-limit`插件实现了基于特定键值实现限流,键值来源可以是 URL 参数、HTTP 请求头
# 配置字段
## 运行属性
插件执行阶段:`默认阶段`
插件执行优先级:`10`
## 配置字段
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
@@ -23,9 +30,9 @@
| query_per_hour | number | 选填,`query_per_second`,`query_per_minute`,`query_per_hour`,`query_per_day` 中选填一项 | - | 允许每小时请求次数 |
| query_per_day | number | 选填,`query_per_second`,`query_per_minute`,`query_per_hour`,`query_per_day` 中选填一项 | - | 允许每天请求次数 |
# 配置示例
## 配置示例
## 识别请求参数 apikey进行区别限流
### 识别请求参数 apikey进行区别限流
```yaml
limit_by_param: apikey
limit_keys:
@@ -35,7 +42,7 @@ limit_keys:
query_per_minute: 100
```
## 识别请求头 x-ca-key进行区别限流
### 识别请求头 x-ca-key进行区别限流
```yaml
limit_by_header: x-ca-key
limit_keys:
@@ -45,29 +52,3 @@ limit_keys:
query_per_hour: 10
```
## 对特定路由或域名开启
```yaml
# 使用 _rules_ 字段进行细粒度规则配置
_rules_:
# 规则一:按路由名称匹配生效
- _match_route_:
- route-a
- route-b
limit_by_header: x-ca-key
limit_keys:
- key: 102234
query_per_second: 10
# 规则二:按域名匹配生效
- _match_domain_:
- "*.example.com"
- test.com
limit_by_header: x-ca-key
limit_keys:
- key: 102234
query_per_second: 100
```
此例 `_match_route_` 中指定的 `route-a``route-b` 即在创建网关路由时填写的路由名称,当匹配到这两个路由时,将使用此段配置;
此例 `_match_domain_` 中指定的 `*.example.com``test.com` 用于匹配请求的域名,当发现域名匹配时,将使用此段配置;
配置的匹配生效顺序,将按照 `_rules_` 下规则的排列顺序,匹配第一个规则后生效对应配置,后续规则将被忽略。

View File

@@ -1,31 +1,36 @@
<p>
English | <a href="README.md">中文</a>
</p>
---
title: Key-based Local Rate Limiting
keywords: [higress,key rate limit]
description: Configuration reference for Key local rate limiting plugin
---
# Description
`key-rate-limit` plugin implements a rate-limiting function based on specific key-values. The key-values may come from URL parameters or HTTP headers.
## Functional Description
The `key-rate-limit` plugin implements rate limiting based on specific key values, which can originate from URL parameters or HTTP request headers.
# Configuration Fields
## Running Properties
Plugin execution phase: `default phase`
Plugin execution priority: `10`
| Name | Type | Requirement | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| limit_by_header | string | Optional. Choose one from following: `limit_by_header`, `limit_by_param`. | - | The name of HTTP header used to obtain key-value used in rate-limiting. |
| limit_by_param | string | Optional. Choose one from following: `limit_by_header`, `limit_by_param`. | - | The name of URL parameter used to obtain key-value used in rate-limiting. |
| limit_keys | array of object | Required | - | Rate-limiting thresholds when matching specific key-values |
## Configuration Fields
Field descriptions of `limit_keys` items:
| Name | Data Type | Required | Default Value | Description |
|-----------------|-----------------|---------------------------------------------------------------|---------------|----------------------------------------------------------------------------------------|
| limit_by_header | string | Optional, choose one from `limit_by_header`, `limit_by_param` | - | Configuration for the source of the rate limiting key value (HTTP request header name) |
| limit_by_param | string | Optional, choose one from `limit_by_header`, `limit_by_param` | - | Configuration for the source of the rate limiting key value (URL parameter name) |
| limit_keys | array of object | Required | - | Configuration for the rate limiting frequency based on matched key values |
| Name | Type | Requirement | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| key | string | Required | - | Value to match of the specific key |
| query_per_second | number | Optional. Choose one from following: `query_per_second`, `query_per_minute`, `query_per_hour`, `query_per_day`. | - | Number of requests allowed per second |
| query_per_minute | number | Optional. Choose one from following: `query_per_second`, `query_per_minute`, `query_per_hour`, `query_per_day`. | - | Number of requests allowed per minute |
| query_per_hour | number | Optional. Choose one from following: `query_per_second`, `query_per_minute`, `query_per_hour`, `query_per_day`. | - | Number of requests allowed per hour |
| query_per_day | number | Optional. Choose one from following: `query_per_second`, `query_per_minute`, `query_per_hour`, `query_per_day`. | - | Number of requests allowed per day |
Explanation of each configuration field in `limit_keys`
# Configuration Samples
| Name | Data Type | Required | Default Value | Description |
|------------------|-----------|-----------------------------------------------------------------------------------------------------|---------------|---------------------------------------|
| key | string | Required | - | Matched key value |
| query_per_second | number | Optional, choose one from `query_per_second`, `query_per_minute`, `query_per_hour`, `query_per_day` | - | Allowed number of requests per second |
| query_per_minute | number | Optional, choose one from `query_per_second`, `query_per_minute`, `query_per_hour`, `query_per_day` | - | Allowed number of requests per minute |
| query_per_hour | number | Optional, choose one from `query_per_second`, `query_per_minute`, `query_per_hour`, `query_per_day` | - | Allowed number of requests per hour |
| query_per_day | number | Optional, choose one from `query_per_second`, `query_per_minute`, `query_per_hour`, `query_per_day` | - | Allowed number of requests per day |
## Use query parameter `apikey` for rate-limiting
## Configuration Examples
### Identify request parameter apikey for differentiated rate limiting
```yaml
limit_by_param: apikey
limit_keys:
@@ -35,7 +40,7 @@ limit_keys:
query_per_minute: 100
```
## Use HTTP header parameter `x-ca-key` for rate-limiting
### Identify request header x-ca-key for differentiated rate limiting
```yaml
limit_by_header: x-ca-key
limit_keys:
@@ -44,28 +49,3 @@ limit_keys:
- key: 308239
query_per_hour: 10
```
## Enable rate-limiting for specific routes or domains
```yaml
# Use _rules_ field for fine-grained rule configurations
_rules_:
# Rule 1: Match by route name
- _match_route_:
- route-a
- route-b
limit_by_header: x-ca-key
limit_keys:
- key: 102234
query_per_second: 10
# Rule 2: Match by domain
- _match_domain_:
- "*.example.com"
- test.com
limit_by_header: x-ca-key
limit_keys:
- key: 102234
query_per_second: 100
```
In the rule sample of `_match_route_`, `route-a` and `route-b` are the route names provided when creating a new gateway route. When the current route names matches the configuration, the rule following shall be applied.
In the rule sample of `_match_domain_`, `*.example.com` and `test.com` are the domain names used for request matching. When the current domain name matches the configuration, the rule following shall be applied.
All rules shall be checked following the order of items in the `_rules_` field, The first matched rule will be applied. All remained will be ignored.

View File

@@ -1,21 +1,32 @@
# 功能说明
---
title: OAuth2 认证
keywords: [higress,oauth2]
description: OAuth2 认证插件配置参考
---
## 功能说明
`OAuth2`插件实现了基于JWT(JSON Web Tokens)进行OAuth2 Access Token签发的能力, 遵循[RFC9068](https://datatracker.ietf.org/doc/html/rfc9068)规范
# 插件配置说明
## 运行属性
插件执行阶段:`认证阶段`
插件执行优先级:`350`
## 配置字段
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------- | --------------- | ------------------------------------------- | ------ | ----------------------------------------------------------- |
| `consumers` | array of object | 必填 | - | 配置服务的调用者,用于对请求进行认证 |
| `_rules_` | array of object | 选填 | - | 配置特定路由或域名的访问权限列表,用于对请求进行鉴权 |
| `issuer` | string | 选填 | Higress-Gateway | 用于填充JWT中的issuer |
| `auth_path` | string | 选填 | /oauth2/token | 指定路径后缀用于签发Token路由级配置时要确保首先能匹配对应的路由 |
| `global_credentials` | bool | 选填 | ture | 是否开启全局凭证即允许路由A下的auth_path签发Token可以用于访问路由B |
| `auth_header_name` | string | 选填 | Authorization | 用于指定从哪个请求头获取JWT |
| `token_ttl` | number | 选填 | 7200 | token从签发后多久内有效单位为秒 |
| `clock_skew_seconds` | number | 选填 | 60 | 校验JWT的exp和iat字段时允许的时钟偏移量单位为秒 |
| `keep_token` | bool | 选填 | ture | 转发给后端时是否保留JWT |
### 认证配置
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------- | --------------- | ------------------------------------------- | ------ | ----------------------------------------------------------- |
| `consumers` | array of object | 必填 | - | 配置服务的调用者,用于对请求进行认证 |
| `issuer` | string | 选填 | Higress-Gateway | 用于填充JWT中的issuer |
| `auth_path` | string | 选填 | /oauth2/token | 指定路径后缀用于签发Token,路由级配置时,要确保首先能匹配对应的路由, 使用 API 管理时,需要创建相同路径的接口 |
| `global_credentials` | bool | 选填 | ture | 在通过 consumer 认证的前提下,允许任意路由签发的凭证访问 |
| `auth_header_name` | string | 选填 | Authorization | 用于指定从哪个请求头获取JWT |
| `token_ttl` | number | 选填 | 7200 | token从签发后多久内有效单位为秒 |
| `clock_skew_seconds` | number | 选填 | 60 | 校验JWT的exp和iat字段时允许的时钟偏移量单位为秒 |
| `keep_token` | bool | 选填 | ture | 转发给后端时是否保留JWT |
| `global_auth` | array of string | 选填(**仅实例级别配置**) | - | 只能在实例级别配置若配置为true则全局生效认证机制; 若配置为false则只对做了配置的域名和路由生效认证机制; 若不配置则仅当没有域名和路由配置时全局 生效(兼容老用户使用习惯) |
`consumers`中每一项的配置字段说明如下:
@@ -25,27 +36,53 @@
| `client_id` | string | 必填 | - | OAuth2 client id |
| `client_secret` | string | 必填 | - | OAuth2 client secret |
`_rules_` 中每一项的配置字段说明如下:
**注意:**
- 对于开启该配置的路由,如果路径后缀和`auth_path`匹配则该路由不会到原目标服务而是用于生成Token
- 如果关闭`global_credentials`,请确保启用此插件的路由不是精确匹配路由,此时若存在另一条前缀匹配路由,则可能导致预期外行为
- 对于通过认证鉴权的请求请求的header会被添加一个`X-Mse-Consumer`字段,用以标识调用者的名称。
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ---------------- | --------------- | ------------------------------------------------- | ------ | -------------------------------------------------- |
| `_match_route_` | array of string | 选填,`_match_route_``_match_domain_`中选填一项 | - | 配置要匹配的路由名称 |
| `_match_domain_` | array of string | 选填,`_match_route_``_match_domain_`中选填一项 | - | 配置要匹配的域名 |
| `allow` | array of string | 必填 | - | 对于符合匹配条件的请求配置允许访问的consumer名称 |
### 鉴权配置(非必需)
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| ----------- | --------------- | ------------------------------------------- | ------ | ----------------------------------------------------------- |
| `allow` | array of string | 选填(**非实例级别配置**) | - | 只能在路由或域名等细粒度规则上配置,对于符合匹配条件的请求,配置允许访问的 consumer,从而实现细粒度的权限控制 |
**注意:**
- 对于开启该配置的路由,如果路径后缀和`auth_path`匹配则该路由到原目标服务而是用于生成Token
- 如果关闭`global_credentials`,请确保启用此插件的路由不是精确匹配路由,此时若存在另一条前缀匹配路由,则可能导致预期外行为
- 若不配置`_rules_`字段,则默认对当前网关实例的所有路由开启认证;
- 对于通过认证鉴权的请求请求的header会被添加一个`X-Mse-Consumer`字段,用以标识调用者的名称。
- 在一个规则里,鉴权配置和认证配置不可同时存在
## 配置示例
### 对特定路由或域名开启
### 路由粒度配置认证
`route-a``route-b`两个路由做如下插件配置:
```yaml
consumers:
- name: consumer1
client_id: 12345678-xxxx-xxxx-xxxx-xxxxxxxxxxxx
client_secret: abcdefgh-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
此时虽然使用同一份配置,但`route-a` 下签发的凭证无法用于访问 `route-b`,反之亦然。
如果希望同一份配置共享凭证访问权限,可以做如下配置:
```yaml
global_credentials: true
consumers:
- name: consumer1
client_id: 12345678-xxxx-xxxx-xxxx-xxxxxxxxxxxx
client_secret: abcdefgh-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
### 全局配置认证,路由粒度进行鉴权
以下配置将对网关特定路由或域名开启 Jwt Auth 认证和鉴权注意如果一个JWT能匹配多个`jwks`,则按照配置顺序命中第一个匹配的`consumer`
在实例级别做如下插件配置:
```yaml
global_auth: false
consumers:
- name: consumer1
client_id: 12345678-xxxx-xxxx-xxxx-xxxxxxxxxxxx
@@ -53,37 +90,54 @@ consumers:
- name: consumer2
client_id: 87654321-xxxx-xxxx-xxxx-xxxxxxxxxxxx
client_secret: hgfedcba-xxxx-xxxx-xxxx-xxxxxxxxxxxx
# 使用 _rules_ 字段进行细粒度规则配置
_rules_:
# 规则一:按路由名称匹配生效
- _match_route_:
- route-a
- route-b
allow:
- consumer1
# 规则二:按域名匹配生效
- _match_domain_:
- "*.example.com"
- test.com
allow:
- consumer2
```
此例 `_match_route_` 中指定的 `route-a``route-b` 即在创建网关路由时填写的路由名称,当匹配到这两个路由时,将允许`name``consumer1`的调用者访问,其他调用者不允许访问;
`route-a``route-b`两个路由做如下插件配置:
此例 `_match_domain_` 中指定的 `*.example.com``test.com` 用于匹配请求的域名,当发现域名匹配时,将允许`name``consumer2`的调用者访问,其他调用者不允许访问。
```yaml
allow:
- consumer1
```
#### 使用 Client Credential 授权模式
`*.exmaple.com``test.com`两个域名做如下插件配置:
**获取 AccessToken**
```yaml
allow:
- consumer2
```
此例指定的 `route-a``route-b` 即在创建网关路由时填写的路由名称,当匹配到这两个路由时,将允许`name``consumer1`的调用者访问,其他调用者不允许访问;
此例指定的 `*.example.com``test.com` 用于匹配请求的域名,当发现域名匹配时,将允许`name``consumer2`的调用者访问,其他调用者不允许访问。
### 网关实例级别开启
以下配置将对网关实例级别开启 OAuth2 认证,所有请求均需要经过认证后才能访问
```yaml
global_auth: true
consumers:
- name: consumer1
client_id: 12345678-xxxx-xxxx-xxxx-xxxxxxxxxxxx
client_secret: abcdefgh-xxxx-xxxx-xxxx-xxxxxxxxxxxx
- name: consumer2
client_id: 87654321-xxxx-xxxx-xxxx-xxxxxxxxxxxx
client_secret: hgfedcba-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
# 请求示例
## 使用 Client Credential 授权模式
### 获取 AccessToken
```bash
# 通过 GET 方法获取
# 通过 GET 方法获取(推荐)
curl 'http://test.com/oauth2/token?grant_type=client_credentials&client_id=12345678-xxxx-xxxx-xxxx-xxxxxxxxxxxx&client_secret=abcdefgh-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
# 通过 POST 方法获取 (需要先匹配到有真实目标服务的路由)
# 通过 POST 方法获取需要先匹配到有真实目标服务的路由,否则网关不会读取请求 Body
curl 'http://test.com/oauth2/token' -H 'content-type: application/x-www-form-urlencoded' -d 'grant_type=client_credentials&client_id=12345678-xxxx-xxxx-xxxx-xxxxxxxxxxxx&client_secret=abcdefgh-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
@@ -96,29 +150,13 @@ curl 'http://test.com/oauth2/token' -H 'content-type: application/x-www-form-url
```
**使用 AccessToken 请求**
### 使用 AccessToken 请求
```bash
curl 'http://test.com' -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6ImFwcGxpY2F0aW9uXC9hdCtqd3QifQ.eyJhdWQiOiJkZWZhdWx0IiwiY2xpZW50X2lkIjoiMTIzNDU2NzgteHh4eC14eHh4LXh4eHgteHh4eHh4eHh4eHh4IiwiZXhwIjoxNjg3OTUxNDYzLCJpYXQiOjE2ODc5NDQyNjMsImlzcyI6IkhpZ3Jlc3MtR2F0ZXdheSIsImp0aSI6IjEwOTU5ZDFiLThkNjEtNGRlYy1iZWE3LTk0ODEwMzc1YjYzYyIsInN1YiI6ImNvbnN1bWVyMSJ9.NkT_rG3DcV9543vBQgneVqoGfIhVeOuUBwLJJ4Wycb0'
```
因为 test.com 仅授权了 consumer2但这个 Access Token 是基于 consumer1 的 `client_id``client_secret` 获取的,因此将返回 `403 Access Denied`
### 网关实例级别开启
以下配置未指定`_rules_`字段,因此将对网关实例级别开启 OAuth2 认证
```yaml
consumers:
- name: consumer1
client_id: 12345678-xxxx-xxxx-xxxx-xxxxxxxxxxxx
client_secret: abcdefgh-xxxx-xxxx-xxxx-xxxxxxxxxxxx
- name: consumer2
client_id: 87654321-xxxx-xxxx-xxxx-xxxxxxxxxxxx
client_secret: hgfedcba-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
# 常见错误码说明
@@ -126,4 +164,3 @@ consumers:
| ----------- | ---------------------- | -------------------------------------------------------------------------------- |
| 401 | Invalid Jwt token | 请求头未提供JWT, 或者JWT格式错误或过期等原因 |
| 403 | Access Denied | 无权限访问当前路由 |

View File

@@ -0,0 +1,138 @@
---
title: OAuth2 Authentication
keywords: [higress,oauth2]
description: OAuth2 authentication plugin configuration reference
---
## Function Description
`OAuth2` plugin implements the capability of issuing OAuth2 Access Tokens based on JWT (JSON Web Tokens), complying with the [RFC9068](https://datatracker.ietf.org/doc/html/rfc9068) specification.
## Runtime Properties
Plugin execution phase: `Authentication Phase`
Plugin execution priority: `350`
## Configuration Fields
### Authentication Configuration
| Name | Data Type | Requirement | Default Value | Description |
| -------------------- | ---------------- | ------------------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `consumers` | array of object | Required | - | Configures the callers of the service for request authentication |
| `issuer` | string | Optional | Higress-Gateway | Used to fill the issuer in the JWT |
| `auth_path` | string | Optional | /oauth2/token | Specifies the path suffix for issuing Tokens. When configured at the routing level, ensure it matches the corresponding route first. When using API management, create an interface with the same path. |
| `global_credentials` | bool | Optional | true | Allows any route to issue credentials for access under the condition of authentication through the consumer. |
| `auth_header_name` | string | Optional | Authorization | Specifies which request header to retrieve the JWT from |
| `token_ttl` | number | Optional | 7200 | The time duration in seconds for which the token is valid after issuance. |
| `clock_skew_seconds` | number | Optional | 60 | Allowed clock skew when verifying the exp and iat fields of the JWT, in seconds. |
| `keep_token` | bool | Optional | true | Indicates whether to keep the JWT when forwarding to the backend. |
| `global_auth` | array of string | Optional (**Instance-level configuration only**) | - | Can only be configured at the instance level. If set to true, the global authentication mechanism takes effect; if false, the authentication mechanism only takes effect for configured domains and routes; if not configured, global effect occurs only when there are no domain and route configurations (compatible with legacy user habits). |
The configuration fields for each item in `consumers` are as follows:
| Name | Data Type | Requirement | Default Value | Description |
| ----------------------- | ------------------| ----------- | ------------------------------------------------- | ---------------------------------- |
| `name` | string | Required | - | Configures the name of the consumer. |
| `client_id` | string | Required | - | OAuth2 client id |
| `client_secret` | string | Required | - | OAuth2 client secret |
**Note:**
- For routes with this configuration enabled, if the path suffix matches `auth_path`, the route will not forward to the original target service but will be used to generate a Token.
- If `global_credentials` is disabled, please ensure that the routes enabling this plugin do not precisely match routes. If there is another prefix-matching route, it may lead to unexpected behavior.
- For requests authenticated and authorized, the request header will have an `X-Mse-Consumer` field added to identify the caller's name.
### Authorization Configuration (Optional)
| Name | Data Type | Requirement | Default Value | Description |
| ----------- | ---------------- | ---------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `allow` | array of string | Optional (**Non-instance-level configuration**) | - | Can only be configured on fine-grained rules such as routes or domains, allowing specified consumers to access requests that meet the matching conditions for fine-grained permission control. |
**Note:**
- Authentication and authorization configurations cannot coexist in one rule.
## Configuration Example
### Route Granularity Configuration Authentication
For the two routes `route-a` and `route-b`, do the following plugin configuration:
```yaml
consumers:
- name: consumer1
client_id: 12345678-xxxx-xxxx-xxxx-xxxxxxxxxxxx
client_secret: abcdefgh-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
At this time, although using the same configuration, the credentials issued under `route-a` cannot be used to access `route-b`, and vice versa.
If you want the same configuration to share credential access permissions, you can configure as follows:
```yaml
global_credentials: true
consumers:
- name: consumer1
client_id: 12345678-xxxx-xxxx-xxxx-xxxxxxxxxxxx
client_secret: abcdefgh-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
### Global Configuration Authentication, Route Granularity Authorization
The following configuration will enable Jwt Auth for specific routes or domains on the gateway. Note that if a JWT matches multiple `jwks`, it will hit the first matching `consumer` in the order of configuration.
At the instance level, do the following plugin configuration:
```yaml
global_auth: false
consumers:
- name: consumer1
client_id: 12345678-xxxx-xxxx-xxxx-xxxxxxxxxxxx
client_secret: abcdefgh-xxxx-xxxx-xxxx-xxxxxxxxxxxx
- name: consumer2
client_id: 87654321-xxxx-xxxx-xxxx-xxxxxxxxxxxx
client_secret: hgfedcba-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
For the routes `route-a` and `route-b`, do the following plugin configuration:
```yaml
allow:
- consumer1
```
For the domains `*.example.com` and `test.com`, do the following plugin configuration:
```yaml
allow:
- consumer2
```
In this example, route names `route-a` and `route-b` refer to the route names filled in when creating the gateway route. When these two routes are matched, it will allow access for the caller with `name` as `consumer1`, and other callers will not be allowed to access.
In this example, the domains `*.example.com` and `test.com` are used to match request domains. When a matching domain is found, it will allow access for the caller with `name` as `consumer2`, while other callers will not be allowed to access.
### Enable at Gateway Instance Level
The following configuration will enable OAuth2 authentication at the gateway instance level, requiring all requests to be authenticated before access.
```yaml
global_auth: true
consumers:
- name: consumer1
client_id: 12345678-xxxx-xxxx-xxxx-xxxxxxxxxxxx
client_secret: abcdefgh-xxxx-xxxx-xxxx-xxxxxxxxxxxx
- name: consumer2
client_id: 87654321-xxxx-xxxx-xxxx-xxxxxxxxxxxx
client_secret: hgfedcba-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
# Request Example
## Using Client Credential Authorization Mode
### Get AccessToken
```bash
# Get via GET method (recommended)
curl 'http://test.com/oauth2/token?grant_type=client_credentials&client_id=12345678-xxxx-xxxx-xxxx-xxxxxxxxxxxx&client_secret=abcdefgh-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
# Get via POST method (requires matching a route with a real target service first, or the gateway will not read the request Body)
curl 'http://test.com/oauth2/token' -H 'content-type: application/x-www-form-urlencoded' -d 'grant_type=client_credentials&client_id=12345678-xxxx-xxxx-xxxx-xxxxxxxxxxxx&client_secret=abcdefgh-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
# Simply get the access_token field from the response:
{
"token_type": "bearer",
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6ImFwcGxpY2F0aW9uXC9hdCtqd3QifQ.eyJhdWQiOiJkZWZhdWx0IiwiY2xpZW50X2lkIjoiMTIzNDU2NzgteHh4eC14eHh4LXh4eHgteHh4eHh4eHh4eHh4IiwiZXhwIjoxNjg3OTUxNDYzLCJpYXQiOjE2ODc5NDQyNjMsImlzcyI6IkhpZ3Jlc3MtR2F0ZXdheSIsImp0aSI6IjEwOTU5ZDFiLThkNjEtNGRlYy1iZWE3LTk0ODEwMzc1YjYzYyIsInN1YiI6ImNvbnN1bWVyMSJ9.NkT_rG3DcV9543vBQgneVqoGfIhVeOuUBwLJJ4Wycb0",
"expires_in": 7200
}
```
### AccessToken Request
```bash
curl 'http://test.com' -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6ImFwcGxpY2F0aW9uXC9hdCtqd3QifQ.eyJhdWQiOiJkZWZhdWx0IiwiY2xpZW50X2lkIjoiMTIzNDU2NzgteHh4eC14eHh4LXh4eHgteHh4eHh4eHh4eHh4IiwiZXhwIjoxNjg3OTUxNDYzLCJpYXQiOjE2ODc5NDQyNjMsImlzcyI6IkhpZ3Jlc3MtR2F0ZXdheSIsImp0aSI6IjEwOTU5ZDFiLThkNjEtNGRlYy1iZWE3LTk0ODEwMzc1YjYzYyIsInN1YiI6ImNvbnN1bWVyMSJ9.NkT_rG3DcV9543vBQgneVqoGfIhVeOuUBwLJJ4Wycb0'
```
# Common Error Code Description
| HTTP Status Code | Error Message | Explanation |
| ---------------- | ----------------------| --------------------------------------------------------------------------- |
| 401 | Invalid Jwt token | JWT not provided in request header, or JWT format is incorrect, or expired, etc. |
| 403 | Access Denied | No permission to access the current route. |

View File

@@ -1,11 +1,18 @@
<p>
<a href="README_EN.md"> English </a> | 中文
</p>
---
title: 请求屏蔽
keywords: [higress,request block]
description: 请求屏蔽插件配置参考
---
# 功能说明
## 功能说明
`request-block`插件实现了基于 URL、请求头等特征屏蔽 HTTP 请求,可以用于防护部分站点资源不对外部暴露
# 配置字段
## 运行属性
插件执行阶段:`鉴权阶段`
插件执行优先级:`320`
## 配置字段
| 名称 | 数据类型 | 填写要求 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
@@ -16,9 +23,9 @@
| blocked_message | string | 选填 | - | 配置请求被屏蔽时返回的 HTTP 应答 Body |
| case_sensitive | bool | 选填 | true | 配置匹配时是否区分大小写,默认区分 |
# 配置示例
## 配置示例
## 屏蔽请求 url 路径
### 屏蔽请求 url 路径
```yaml
block_urls:
- swagger.html
@@ -33,7 +40,7 @@ curl http://example.com?foo=Bar
curl http://exmaple.com/Swagger.html
```
## 屏蔽请求 header
### 屏蔽请求 header
```yaml
block_headers:
- example-key
@@ -47,7 +54,7 @@ curl http://example.com -H 'example-key: 123'
curl http://exmaple.com -H 'my-header: example-value'
```
## 屏蔽请求 body
### 屏蔽请求 body
```yaml
block_bodies:
- "hello world"
@@ -61,30 +68,8 @@ curl http://example.com -d 'Hello World'
curl http://exmaple.com -d 'hello world'
```
## 对特定路由或域名开启
```yaml
# 使用 _rules_ 字段进行细粒度规则配置
_rules_:
# 规则一:按路由名称匹配生效
- _match_route_:
- route-a
- route-b
block_bodies:
- "hello world"
# 规则二:按域名匹配生效
- _match_domain_:
- "*.example.com"
- test.com
block_urls:
- "swagger.html"
block_bodies:
- "hello world"
```
此例 `_match_route_` 中指定的 `route-a``route-b` 即在创建网关路由时填写的路由名称,当匹配到这两个路由时,将使用此段配置;
此例 `_match_domain_` 中指定的 `*.example.com``test.com` 用于匹配请求的域名,当发现域名匹配时,将使用此段配置;
配置的匹配生效顺序,将按照 `_rules_` 下规则的排列顺序,匹配第一个规则后生效对应配置,后续规则将被忽略。
# 请求 Body 大小限制
## 请求 Body 大小限制
当配置了 `block_bodies` 时,仅支持小于 32 MB 的请求 Body 进行匹配。若请求 Body 大于此限制,并且不存在匹配到的 `block_urls``block_headers` 项时,不会对该请求执行屏蔽操作
当配置了 `block_bodies` 时,若请求 Body 超过全局配置 DownstreamConnectionBufferLimits将返回 `413 Payload Too Large`

View File

@@ -1,24 +1,28 @@
<p>
English | <a href="README.md">中文</a>
</p>
---
title: Request Blocking
keywords: [higress,request block]
description: Request blocking plugin configuration reference
---
## Function Description
The `request-block` plugin implements HTTP request blocking based on features such as URL, request headers, etc. It can be used to protect certain site resources from being exposed to the outside.
# Description
`request-block` plugin implements a request blocking function based on request characteristics such as URL and request header. It can be used to protect internal resources from unauthorized access.
## Running Attributes
Plugin Execution Stage: `Authentication Stage`
# Configuration Fields
Plugin Execution Priority: `320`
| Name | Type | Requirement | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| block_urls | array of string | Optional. Choose one from following: `block_urls`, `block_headers`, `block_bodies` | - | HTTP URLs to be blocked. |
| block_headers | array of string | Optional. Choose one from following: `block_urls`, `block_headers`, `block_bodies` | - | HTTP request headers to be blocked. |
| block_bodies | array of string | Optional. Choose one from following: `block_urls` ,`block_headers`, `block_bodies` | - | HTTP request bodies to be blocked. |
| blocked_code | number | Optional | 403 | HTTP response status code to be sent when corresponding request is blocked. |
| blocked_message | string | Optional | - | HTTP response body to be sent when corresponding request is blocked. |
| case_sensitive | bool | Optional | true | Whether to use case-senstive comparison when matching. Enabled by default. |
## Configuration Fields
| Name | Data Type | Fill Requirement | Default Value | Description |
|--------------------|--------------------|---------------------------------------------------------|---------------|------------------------------------------------------------|
| block_urls | array of string | Optional, at least one of `block_urls`, `block_headers`, `block_bodies` must be filled | - | Configure strings for matching URLs that need to be blocked |
| block_headers | array of string | Optional, at least one of `block_urls`, `block_headers`, `block_bodies` must be filled | - | Configure strings for matching request headers that need to be blocked |
| block_bodies | array of string | Optional, at least one of `block_urls`, `block_headers`, `block_bodies` must be filled | - | Configure strings for matching request bodies that need to be blocked |
| blocked_code | number | Optional | 403 | Configure the HTTP status code returned when a request is blocked |
| blocked_message | string | Optional | - | Configure the HTTP response body returned when a request is blocked |
| case_sensitive | bool | Optional | true | Configure whether matching is case-sensitive, default is case-sensitive |
# Configuration Samples
## Block Specific Request URLs
## Configuration Example
### Blocking Request URL Paths
```yaml
block_urls:
- swagger.html
@@ -26,65 +30,39 @@ block_urls:
case_sensitive: false
```
According to the configuration above, following requests will be blocked:
Based on this configuration, the following requests will be denied access:
```bash
curl http://example.com?foo=Bar
curl http://exmaple.com/Swagger.html
```
## Block Specific Request Headers
### Blocking Request Headers
```yaml
block_headers:
- example-key
- example-value
```
According to the configuration above, following requests will be blocked:
Based on this configuration, the following requests will be denied access:
```bash
curl http://example.com -H 'example-key: 123'
curl http://exmaple.com -H 'my-header: example-value'
```
## Block Specific Request Bodies
### Blocking Request Bodies
```yaml
block_bodies:
- "hello world"
case_sensitive: false
```
According to the configuration above, following requests will be blocked:
Based on this configuration, the following requests will be denied access:
```bash
curl http://example.com -d 'Hello World'
curl http://exmaple.com -d 'hello world'
```
## Only Enable for Specific Routes or Domains
```yaml
# Use _rules_ field for fine-grained rule configurations
_rules_:
# Rule 1: Match by route name
- _match_route_:
- route-a
- route-b
block_bodies:
- "hello world"
# Rule 2: Match by domain
- _match_domain_:
- "*.example.com"
- test.com
block_urls:
- "swagger.html"
block_bodies:
- "hello world"
```
In the rule sample of `_match_route_`, `route-a` and `route-b` are the route names provided when creating a new gateway route. When the current route names matches the configuration, the rule following shall be applied.
In the rule sample of `_match_domain_`, `*.example.com` and `test.com` are the domain names used for request matching. When the current domain name matches the configuration, the rule following shall be applied.
All rules shall be checked following the order of items in the `_rules_` field, The first matched rule will be applied. All remained will be ignored.
## Request Body Size Limit
When `block_bodies` is configured, only request bodies smaller than 32 MB are supported for matching. If the request body exceeds this limit and there are no matching `block_urls` or `block_headers`, the blocking operation will not be executed for that request.
# Maximum Request Body Size Limitation
When `block_bodies` is configured, body matching shall only be performed when its size is smaller than 32MB. If not, and no `block_urls` or `block_headers` configuration is matched, the request won't be blocked.
When `block_bodies` is configured, if the size of request body exceeds the global configuration of DownstreamConnectionBufferLimits, a ``413 Payload Too Large`` response will be returned.
When `block_bodies` is configured and the request body exceeds the global configuration DownstreamConnectionBufferLimits, it will return `413 Payload Too Large`.

View File

@@ -1,11 +1,14 @@
# 功能说明
## 功能说明
**此插件已经废弃从1.4版本开始Higress 从根本上解决了这一问题,不再需要此插件**
`http2-misdirect`插件用于解决网关开启 HTTP2 时,因为浏览器复用连接导致访问出现 404 等问题。
# 插件原理
## 插件原理
HTTP2 协议允许两个不同域名的请求,在域名解析到相同 IP并且使用了相同证书的情况下复用同一条连接。这在一些特殊场景会导致复用连接的请求发送给了错误的 Virtual Host 进行处理,从而导致出现 404 等问题。
本插件基于`HTTP/2 RFC 7540``9.1.1``9.1.2`章节描述,在发现请求 SNI 与当前 Virtual Host 不匹配时,发送 HTTP 421 状态码,强制浏览器新建连接,并根据当前请求域名生成匹配的 SNI从而让网关能正确处理路由。
# 浏览器兼容性
## 浏览器兼容性
`Safari` 浏览器 `15.1` 版本以下不支持 HTTP 421 状态码,若有此类客户端访问场景,建议对相应域名关闭 HTTP2 的 ALPN