# @cloudbase/oauth 中文文档

规范地址：https://npmcn.com/package/%40cloudbase/oauth/

版本：3\.9\.3
npm 元数据更新时间：2026-11-16T10:14:20.353Z
中文译文更新时间：2026-11-16T10:19:18.740Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40cloudbase/oauth
原文对照：https://npmcn.com/package/%40cloudbase/oauth/?lang=original

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：1.9 MB，116 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- 首次发布：2021-08-19T12:42:29.484Z
- 最新版本发布：2026-11-16T10:14:20.138Z
- 近 30 天下载量：12056（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：384（近 12 个月 143 个）

## 中文简介

云底 javascript sdk 认证计算符

## 安装

```sh
npm install @cloudbase/oauth
```

也可以使用：`pnpm add @cloudbase/oauth`、`yarn add @cloudbase/oauth`、`bun add @cloudbase/oauth`

## README

# Oauth

提供 oauth2 的登录相关功能。

## 主要模块

OAuth2Client oauth2 基础模块

Auth 登录相关模块

## 使用示例

### 初始化对象

```typescript
const authOptions = {
    apiOrigin: "服务域名",
    clientId: "客户端ID"
}
const auth = new Auth(authOptions)
```

```typescript
import { initializeClient } from "@xbasesdk/xbase"
const config = {
    env: "xbase-4gh5dh6nf62145a9"
}
const client = initializeClient(config)
// 调用API
const loginState = await client.auth.hasLoginState()
// 获取 accessToken
const accessToken = await client.oAuth2Client.getAccessToken()

// 用 OIDC Token 用自己的API
export interface ExampleData {
    result?: string
}
const data = await client.oAuth2Client.request<ExampleData>(
    "https://example.com",
    { withCredentials: true }
)
console.log(data.result)



import {initializeApp} from '@clodbasesdk/oauth/app';
import {getAuth} from '@clodbasesdk/oauth/auth';
export const config = {
    env: 'env-4gh5dh6nf62145a9'
};
const app = initializeApp(config)
const auth = getAuth(app)
// 调用API
const loginState = await auth.hasLoginState()
```

### 账号登录

```typescript
auth.signIn({
    username: "test",
    password: "test"
})
```

### 手机验证码登录/注册

```typescript
const phoneNumber = "10012341234"
// 短信验证码
const verificationCode = "******"
const verification = await auth.getVerification({
    phone_number: "+86 " + phoneNumber,
    target: "ANY"
})

let verifyResult = await auth.verify({
    verification_code: verificationCode,
    verification_id: verification ? verification.verification_id : ""
})
let isUser = verification ? verification.is_user : false

let result
if (isUser) {
    result = await auth.signIn({
        username: "+86 " + phoneNumber,
        verification_code: verificationCode,
        verification_token: verifyResult.verification_token
    })
} else {
    result = await auth.signUp({
        phone_number: "+86 " + phoneNumber,
        password: "*******",
        verification_code: verificationCode,
        verification_token: verifyResult.verification_token,
        local: "zh-cn",
        name: "100****1234"
    })
}
```

### 错误处理

```typescript
try {
    await auth.verify({
        verification_code: verificationCode,
        verification_id: verification ? verification.verification_id : ""
    })
} catch (error) {
    if (error && error.error_uri === "/v1/auth/verification/verify") {
        switch (error.error) {
            case "not_found": {
                result = i18n.translate("error", "User Not Found")
                break
            }
            case "invalid_password": {
                if (error.details !== undefined && error.details.length > 0) {
                    result =
                        i18n.translate("error", "Certification failed, you still have") +
                        error.details[0].limit_remaining +
                        i18n.translate("error", "chances. You can also") +
                        "" +
                        i18n.translate("error", "Reset Login Password") +
                        "</a>"
                } else {
                    result = i18n.translate("error", "Password does not match")
                }
                break
            }
            case "user_pending": {
                result = i18n.translate("error", "The account is not activated")
                break
            }
            case "user_blocked": {
                result = i18n.translate("error", "Account has been disabled")
                break
            }
            case "invalid_status": {
                if (error.details !== undefined && error.details.length > 0) {
                    let s = error.details[0].retry_delay
                    s = s.substring(0, s.length - 1)
                    s = parseInt(s)
                    result =
                        i18n.translate(
                            "error",
                            "The password input error has reached the upper limit and the account will be locked "
                        ) +
                        (s < 3600
                            ? s / 60 + i18n.translate("error", "minute")
                            : s / 3600 + i18n.translate("error", "hour"))
                } else {
                    result = i18n.translate(
                        "error",
                        "Account has been temporarily locked"
                    )
                }
                break
            }
            case "invalid_two_factor": {
                result = i18n.translate(
                    "error",
                    "Secondary authentication code does not match or has expired"
                )
                break
            }
            case "invalid_two_factor_recovery": {
                result = i18n.translate(
                    "error",
                    "Recovery code does not match or has expired"
                )
                break
            }
            default: {
                result = i18n.translate("error", "unknown")
                break
            }
        }
    }
}
```

## [更新日志](https://npmcn.com/package/%40cloudbase/oauth/CHANGELOG.md)

## 常见问题

### @cloudbase/oauth 是什么？

云底 javascript sdk 认证计算符

### 如何安装 @cloudbase/oauth？

在项目目录运行 npm install @cloudbase/oauth，或使用 pnpm add / yarn add / bun add。

### @cloudbase/oauth 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @cloudbase/oauth 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @cloudbase/oauth 可以商用吗？

@cloudbase/oauth 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @cloudbase/oauth 的下载量有多少？

根据 npm 官方下载统计，@cloudbase/oauth 在 2026/10/10 – 2026/11/08 这 30 天内被下载 12,056 次，日均约 402 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @cloudbase/oauth 还在维护吗？

最新版本 3\.9\.3 发布于 2026/11/16（今天）；至今共发布 384 个版本，其中过去 12 个月发布了 143 个；首次发布于 2021/08/19。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

