# OAuth2 授权页面因客户端应用名称包含恶意脚本导致跨站脚本攻击

- **ID:** `security/oauth2-consent-page-xss-via-client-name`
- **领域:** security
- **类别:** auth_error
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

OAuth2 授权服务器在授权页面上渲染客户端应用名称时未进行正确的 HTML 转义，允许攻击者注册一个包含 JavaScript 的客户端名称，从而在用户浏览器中执行恶意脚本。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| OAuth2 2.0 | active | — | — |
| Spring Security 5.7.10 | active | — | — |
| Keycloak 21.0.0 | active | — | — |
| Auth0 Node.js SDK 2.42.0 | active | — | — |

## 解决方案

1. ```
   在授权页面上渲染客户端应用名称之前，应用 HTML 实体编码。在 Java 与 Spring Security 中，在模板中使用 `HtmlUtils.htmlEscape(clientName)`。对于 Keycloak，覆盖授权表单模板 (consent.ftl) 并使用 `<#escape x as x?html>${client.clientName}</#escape>` 转义 `${client.clientName}`。
   ```
2. ```
   在注册时验证客户端名称，拒绝任何包含 HTML 标签或脚本字符的名称。使用白名单方法：仅允许字母数字字符、空格和基本标点符号。示例正则表达式：`^[a-zA-Z0-9\s\-_\.]+$`。
   ```
3. ```
   如果客户端名称用于动态属性，特别针对 JavaScript 上下文实现输出编码。使用 OWASP Java Encoder 等库：`Encoder.forJavaScript(clientName)`。
   ```

## 无效尝试

- **Add Content-Security-Policy header to block inline scripts** — CSP does not prevent the injection itself; if the client name is rendered in a href attribute or event handler, CSP may not block it, and the script still executes in some contexts. (40% 失败率)
- **Sanitize client name by removing all HTML tags with a simple regex** — Attackers can bypass regex-based sanitization with obfuscated payloads (e.g., using Unicode characters or event handlers like onerror). (35% 失败率)
- **Use a WAF to filter malicious client names during registration** — WAF rules are often bypassed by encoding the payload (e.g., base64 or URL encoding), and the consent page still renders the name unsafely. (50% 失败率)
