2026-08-06 16:57:59.086616+08 / restful-api

API Security

A practical guide to OAuth 2.0, TLS, scopes, JWT token sizing, and permission naming for RESTful APIs.

Restful ApiApi DesignOpenapi

API Security

API security is a critical part of RESTful API design. APIs must protect resources against unauthorized access, data leakage, and misuse.

This chapter defines security requirements and recommendations for authentication, authorization, and permission management.


Secure External API Endpoints with OAuth 2.0 over TLS

External API endpoints MUST be protected using OAuth 2.0 over TLS.

OAuth 2.0 provides a standard mechanism for authentication and authorization, while TLS ensures confidentiality and integrity of data transmitted between clients and servers.

External APIs typically include:

  • Public APIs exposed to external consumers.
  • Partner APIs shared with external organizations.
  • Enterprise APIs accessed across different systems.

Internal-only APIs may use platform-specific security mechanisms depending on the deployment environment.

API security definitions SHOULD be explicitly described in the OpenAPI specification.

Example:

yaml
components:
  securitySchemes:
    oauth2:
      type: oauth2
      description: >
        API resources are protected using OAuth 2.0
        with the client credentials grant flow.
      flows:
        clientCredentials:
          tokenUrl: https://identity.example.com/oauth2/token
          scopes:
            order-service.read:
              Access permission to read order information.
            order-service.write:
              Access permission to modify order information.

The above example defines OAuth 2.0 using the client credentials flow, which is commonly used for machine-to-machine API communication.

The scopes section defines permissions that can later be assigned to API operations for authorization control.

TLS Requirements

TLS configuration SHOULD follow organizational security requirements, including:

  • Supported TLS versions.
  • Approved cipher suites.
  • Certificate management policies.

Exception

OAuth 2.0 may not be required when:

  • Mutual TLS (mTLS) is used for authentication.
  • The API does not require user identity or permission-based access control.

Define and Assign Permissions (Scopes) for OAuth 2.0

APIs protected by OAuth 2.0 MUST define permissions through scopes.

Each protected API operation SHOULD have at least one assigned permission.

Example:

yaml
paths:
  /orders/{orderId}:
    get:
      summary: Retrieve order information
      security:
        - oauth2:
            - order-service.read

Permissions SHOULD be designed at service level instead of creating excessive fine-grained permissions.

For most scenarios, the following permission model is sufficient:

text
<service-name>.read
<service-name>.write

Examples:

Application Resource Access Type Scope Example Description
order-service read order-service.read Read access for the service
order-service write order-service.write Write access for the service
report-service events read report-service.events.read Read access for specific resource

Resource-specific permissions SHOULD only be introduced when different resources require independent authorization boundaries.


JWT Token Size Considerations

Although the JWT specification does not define a maximum token size, practical infrastructure limitations exist.

Because JWT tokens are transmitted through HTTP headers:

  • HTTP servers usually have maximum header size limits.
  • Large JWT tokens may cause request failures.
  • The total token size SHOULD be controlled carefully.

Recommended practices:

  • Keep JWT tokens reasonably small.
  • Avoid unnecessary claims.
  • Avoid excessive numbers of scopes.
  • Review permission design when scopes become too large.

OAuth 2.0 Scope Naming Convention

OAuth 2.0 scope names SHOULD follow a consistent naming convention.

Recommended format:

text
<permission> ::= <standard-permission>
               | <resource-permission>
               | <pseudo-permission>


<standard-permission> ::= <application-id>.<access-mode>

<resource-permission> ::= <application-id>.<resource-name>.<access-mode>

<pseudo-permission> ::= uid


<application-id> ::= [a-z][a-z0-9-]*

<resource-name> ::= [a-z][a-z0-9-]*

<access-mode> ::= read | write

Examples

Service-level permissions:

text
order-service.read
order-service.write

Resource-level permissions:

text
report-service.events.read
report-service.events.write

Identity-based permission:

text
uid

A consistent scope naming strategy improves:

  • Permission readability.
  • Security governance.
  • Long-term maintainability.
  • Authorization scalability.
text

---

# 中文版本

```markdown
# 4. API 安全

API 安全是 RESTful API 设计的重要组成部分。

API 必须保护业务资源,避免未授权访问、数据泄露以及非法调用。

本章节定义 API 在身份认证、权限控制以及访问管理方面的设计要求。

---

## 外部 API 端点应使用 TLS 上的 OAuth 2.0 进行保护

所有面向外部开放的 API 端点都应该通过 TLS 环境下的 OAuth 2.0 机制进行保护。

OAuth 2.0 提供标准化的身份认证和授权机制,TLS 用于保证通信过程中的数据机密性和完整性。

外部 API 通常包括:

- 面向公网用户开放的 API;
- 面向合作伙伴开放的 API;
- 企业内部跨系统访问的 API。

仅内部使用的 API 可以根据具体运行环境采用其他安全机制。

API 安全定义应该在 OpenAPI 文档中明确声明。

示例:

```yaml
components:
  securitySchemes:
    oauth2:
      type: oauth2
      description: >
        API 资源使用 OAuth 2.0 保护,
        使用 client credentials 授权模式。
      flows:
        clientCredentials:
          tokenUrl: https://identity.example.com/oauth2/token
          scopes:
            order-service.read:
              读取订单信息的访问权限。
            order-service.write:
              修改订单信息的访问权限。

上述示例使用 OAuth 2.0 Client Credentials Flow。

该模式通常用于:

  • 服务调用服务(Machine-to-Machine);
  • 后端系统之间的 API 调用。

scopes 用于定义 API 权限,并在接口级别进行授权控制。


TLS 安全要求

TLS 配置应该符合组织安全要求,包括:

  • 支持的 TLS 版本;
  • 加密算法套件;
  • 证书管理策略。

OAuth 2.0 例外情况

以下情况可以不使用 OAuth 2.0:

  • 使用 mTLS(双向 TLS)完成身份认证;
  • API 不需要基于用户身份或权限进行访问控制。

使用 OAuth 2.0 时必须定义权限(Scopes)

使用 OAuth 2.0 保护资源的 API 必须通过 Scope 定义访问权限。

每个受保护的 API 操作都应该关联至少一个权限。

示例:

yaml
paths:
  /orders/{orderId}:
    get:
      summary: 查询订单信息
      security:
        - oauth2:
            - order-service.read

权限设计应该优先采用服务级权限,而不是创建大量细粒度权限。

大多数场景下:

text
<service-name>.read
<service-name>.write

已经可以满足访问控制需求。

示例:

服务 资源 操作 Scope 示例 描述
order-service read order-service.read 服务读取权限
order-service write order-service.write 服务修改权限
report-service events read report-service.events.read 指定资源读取权限

只有当不同资源需要完全不同的授权边界时,才应该设计资源级权限。


JWT Token 大小限制

虽然 JWT 标准没有规定 Token 最大长度,但实际运行环境存在限制。

由于 JWT 通常通过 HTTP Header 传输:

  • HTTP Server 通常限制 Header 最大大小;
  • 过大的 JWT 可能导致请求失败;
  • Scope 数量过多会导致 Token 膨胀。

建议:

  • 控制 JWT Token 大小;
  • 避免加入无意义 Claim;
  • 避免定义过多 Scope;
  • 当权限数量快速增长时重新评估权限模型。

OAuth 2.0 Scope 命名规范

OAuth 2.0 Scope 名称应该遵循统一命名规则。

推荐格式:

text
<permission> ::= <standard-permission>
               | <resource-permission>
               | <pseudo-permission>


<standard-permission> ::= <application-id>.<access-mode>

<resource-permission> ::= <application-id>.<resource-name>.<access-mode>

<pseudo-permission> ::= uid


<application-id> ::= [a-z][a-z0-9-]*

<resource-name> ::= [a-z][a-z0-9-]*

<access-mode> ::= read | write

示例

服务级权限:

text
order-service.read
order-service.write

资源级权限:

text
report-service.events.read
report-service.events.write

身份标识权限:

text
uid

统一的 Scope 命名规范可以提升:

  • 权限可读性;
  • 安全治理能力;
  • 长期维护能力;
  • 授权体系扩展能力。
API Security | Remi Resume