# @descope/react-native-sdk 中文文档

规范地址：https://npmcn.com/package/%40descope/react-native-sdk/

版本：0\.13\.1
npm 元数据更新时间：2026-09-08T12:51:56.744Z
中文译文更新时间：2026-11-12T00:54:04.962Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40descope/react-native-sdk
原文对照：https://npmcn.com/package/%40descope/react-native-sdk/?lang=original
项目主页：https://github.com/descope/descope-react-native#readme
源码仓库：https://github.com/descope/descope-react-native

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

- 包体积（解压后）：1 MB，240 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>= 18\.18\.0
- 运行依赖：2 个
- peer 依赖：react \*，react-native \*
- 首次发布：2023-10-10T13:16:34.059Z
- 最新版本发布：2026-09-08T12:51:56.396Z
- 近 30 天下载量：101047（2026-10-12 至 2026-11-10，npm 官方下载统计）
- 已发布版本数：18（近 12 个月 9 个）

## 中文简介

反射的SDK望远镜

## 安装

```sh
npm install @descope/react-native-sdk
```

也可以使用：`pnpm add @descope/react-native-sdk`、`yarn add @descope/react-native-sdk`、`bun add @descope/react-native-sdk`

## README

# 反应原生的扫描器 SDK

React Industrial的Descope SDK为在React Industrial上书写的应用程序提供了方便的Descope访问权. 你可以读更多关于 [望远镜网站](https://descope.com/)。 。 。 .

## 兼容性

SDK是根据以下所列版本开发并测试的. 旧版本可能有效,但未得到官方支持.

| 所需经费 | 版本 |
| --- | --- |
| 原生反应 | `0.78` (当前发布) - 工作 `>= 0.74` 通过本地对接层 |
| 反应 | `19.0` (携带回放原生0.78) |
| 节点.js | `>= 18.18.0` |
| iOS 部署目标 | `>= 13.0` |
| X代码 | `>= 15.0` (通过测试) `26.4`(中文(简体) ) |
| 机器人 `minSdkVersion` | `24` |
| 机器人 `compileSdkVersion` | `35` |
| Java / Kotlin JVM 目标 | `17` |

**结构 :** 该图书馆的写作与遗产桥建筑相对. 在使用 React Industrial 的新架构的应用程序上( 自此默认) `0.76`),库由接口层透明地包裹-不需要主机配置. 向较新建筑的迁移是路线图.

**展览 :** 博览会得到了支持,但因为图书馆船本土代码要求 [自定义开发](https://docs.expo.dev/develop/development-builds/introduction/) 或空工作流程 - 博览 Go是一个预设的应用程序,因此无法工作.

**XCode 26+: (英语)** XCode 新版本可能导致 `fmt` 与 Xcode 26 的 clang 的相容性问题, 并影响任何 React Environment app - 不是这个 SDK 的特指. 它固定在上游的React Industrial `0.84+` 一艘新船 `fmt`。如果您在较早的版本上,您需要补齐您的iOS构建. 见 [排除故障区域](https://npmcn.com/package/%40descope/react-native-sdk/#readme-fixing-xcode-26-compatibility-issues) 用于详细的补丁步骤.

## 所需资源

-   望远镜 `Project ID` 用于使用SDK。 硂т [descope 控制台中的项目页面](https://app.descope.com/settings/project)。 。 。 .

## 安装 SDK

以 :

```bash
yarn add @descope/react-native-sdk
# or
npm i --save @descope/react-native-sdk
```

在锁定iOS时,确保导航进入 `ios` 文件夹并安装依赖 :

```bash
pod install
```

## 使用量

### 与 Auth 提供方包装您的应用程序

```js
import { AuthProvider } from '@descope/react-native-sdk'

const AppRoot = () => {
  return (
    <AuthProvider
      projectId="my-project-id"
      // If the Descope project manages the token response in cookies, a custom domain
      // must be configured (e.g., https://auth.app.example.com)
      // and should be set as the baseUrl property.
      // baseUrl = "https://auth.app.example.com"
    >
      <App />
    </AuthProvider>
  )
}
```

## 日志

您可以配置 SDK , 通过提供日志到 `AuthProvider`数字 :

```js
const logger = {
  log: (message) => MyMonitoringService.info(message),
  debug: (message) => MyMonitoringService.debug(message),
  warn: (message) => MyMonitoringService.warn(message),
  error: (message) => MyMonitoringService.error(message),
}

<AuthProvider projectId="my-project-id" logger={logger}>
  <App />
</AuthProvider>
```

这个 `logger` prop 接受任何执行对象 `log`, (中文(简体) ), `debug`, (中文(简体) ), `warn`,以及 `error` 使用方法,便于与任何监测或可观察服务连接。 开发期间可以通过 `console` 直接用于快速调试.

日志接收来自JavaScript层和原生SDK层(iOS/Android)的信息,因此所有SDK活性会被捕获,包括流执行和网络呼叫.

## 会话管理

这个 `useSession` 钩子用于管理一个应用程序的认证用户会话.

会话管理器负责加载、保存和自动刷新 会议闭幕。 自动刷新是背景感知和默认状态 。 过 `autoRefresh={false}` 改为 `<AuthProvider>` 如果你需要选择退出.

当用户在流程中成功完成一个符号时,您应该设置 `DescopeSession` 作为会话管理器的活跃会话.

```js
import { useDescope, useSession } from '@descope/react-native-sdk'

const descope = useDescope()
const { manageSession } = useSession()

const resp = await descope.otp.email.verify('andy@example.com', '123456')
manageSession(resp.data)
```

然后可以随时使用会话管理器来确保会话 并用一个 无记名代号授权信头.

```js
const { session } = useSession()

const res = await fetch('/path/to/server/api', {
  headers: {
    Authorization: `Bearer ${session.sessionJwt}`,
  },
})
```

在重新启动申请时 `AuthProvider` 组件将自动加载任何已存在的 届会。 一旦 `isSessionLoading` 旗帜是 `false`,您可以检查是否有可用的会话(即认证用户).

当用户想要从应用程序中签名时,我们撤销 正在运行的会话,并由会话管理器清除:

```js
import { useDescope, useSession } from '@descope/react-native-sdk'

const descope = useDescope()
const { session, clearSession } = useSession()

await descope.logout(session.refreshJwt)
await clearSession(resp.data)
```

### 访问会话

会议信息可通过下列网站获取: `useSession` 钩子,但也可能很方便 用于使用 `getCurrentSessionToken()`, (中文(简体) ), `getCurrentRefreshToken()` 财务报告和审定财务报表 `getCurrentUser()` 帮助函数 . 这些功能可在组件制成寿命周期之外使用. 例如,这或许有助于在所有经认证的请求中添加一个授权标题.

### 刷新会话

大多数应用程序不再需要手动刷新会话 - 自动刷新 使会议在背景中保持温暖并持续进行 由于在安全存储中的持续会话在下一个 自动发射和重新安排 下面的图案,当你有 禁用自动更新通过 `autoRefresh={false}`,或者当你需要保证 在特定时刻举行新会,而不论自动更新的时间安排 例如,在无法容忍的请求之前 `401`) (中文(简体) ).

复会的指导性原则是相同的,无论具体内容如何 应用架构或网络框架.

在每次认证请求之前, 请将您的授权头添加到请求中 期待得到它。 作为优化,也可以调用 `refreshSessionIfAboutToExpire()`。 。 。 . 如果会话符号即将过期, 或已经过期, 此同步函数将先发制人地刷新它 . 密码可能是这样的:

```js
// ... before every authenticated request
try {
  // refresh if needed
  await refreshSessionIfAboutToExpire()
} catch (e) {
  // fail silently - as this shouldn't affect the request being performed
}

// add authorization header
request.headers.Authorization = `Bearer ${getCurrentSessionToken()}`
```

每次错误响应后 - 如果服务器回复到会话符号无效, 即 . `401` 或等效的,请尝试刷新会话符并重复请求。 否则, 清除会话并提示用户重新认证. 密码可能是这样的

```js
// ... on every error response
// assuming 401 is returned ONLY when the session JWT is invalid
if (error.status === 401) {
  try {
    const resp = await descope.refresh(getCurrentRefreshToken())
    await updateTokens(resp.data.sessionJwt, resp.data.refreshJwt)

    // you can now retry the original request
    // NEED TO MAKE SURE THAT THIS RETRY IS ONLY PERFORMED ONCE
    // otherwise, an endless loop of failed requests might occur
    retryRequest()
  } catch (e) {
    // clear the session as the user must re-authenticate
  }
}
```

**重要说明**:如果你认为有必要通过一个参考 `refreshSessionIfAboutToExpire()` `updateTokens()` 财务报告和审定财务报表 `descope` 从 `useSession` 钩入一些网络组件, 确保 使用生命周期感知方法完成的. 密码可能是这样的:

```js
const descope = useDescope()
const { isSessionLoading, refreshSessionIfAboutToExpire, updateTokens } = useSession()

React.useEffect(() => {
  if (!isSessionLoading) {
    setUpNetworkRefresh(refreshSessionIfAboutToExpire, updateTokens, descope)
  }
}, [isSessionLoading refreshSessionIfAboutToExpire, updateTokens, descope])
```

## 运行中流程

我们可以通过建立和运行Flows来认证用户. 潮流建在望镜中 [流程编辑器](https://app.descope.com/flows)编辑器允许您轻松 定义将用户通过它们的行为和用户界面 认证之行. 更多关于它,在地镜 [开始中](https://docs.descope.com/build/guides/gettingstarted/) 向导.

### 设置 # 1: 定义并托管您的流量

在运行一流之前,必须首先定义并托管. 每个项目 带有预定义的流出框中。 您可以自定义您的流量以适应您的需要 并主持它。 跟随 页:1 [开始中](https://docs.descope.com/build/guides/gettingstarted/) 详细情况指南. 你可以自己主持流量,也可以利用Descope主机流量页面. 更多关于它的内容 [这里](https://docs.descope.com/customize/auth/oidc/#hosted-flow-application)。 。 。 . 也可以检查 [自动重播](https://github.com/descope/auth-hosting)。 。 。 .

### (OPTIONAL) 设置 2.1: 在Android上启用魔法链接和OAuth(社交)的 App Links

一些认证方法依赖于离开应用程序的上下文来认证 用户,例如导航到身份提供者的网站进行OAuth(社会)认证, 或者通过电子邮件或短信接收到魔法链接。 如果您不打算使用这些认证 方法,你可以跳过这个步骤。 否则,为了让用户回来 对您的应用程序,设置 [应用链接](https://developer.android.com/training/app-links#android-app-links) 需要时间. 一旦你有一个域设置 [已核实](https://developer.android.com/training/app-links/verify-android-applinks) 用于发送 App 链接, 您需要处理您的应用程序中的深层链接 并恢复流量.

### (OPTIONAL) 设置 #2.2:支持魔法链接重定向于iOS

在流量中支持"魔法链接"认证需要一些平台特定设置: 你需要这样 [支持关联域](https://developer.apple.com/documentation/xcode/supporting-associated-domains?language=swift)。 。 。 .

无论平台如何,需要另外一条路径来专门处理魔法链接重定向. 为了这个研究,让我们命名 这个 `/magiclink`

#### 定义深链接处理

_此代码示例显示如何处理应用程序链接 - 您可以自定义以适应您的应用程序_

```js
import { FlowView } from '@descope/react-native-sdk'

const [deepLink, setDeepLink] = useState('')

useEffect(() => {
  Linking.addEventListener('url', async (event) => {
    if (event.url === 'https://my-deep-link-for-authenticating.com') {
      setDeepLink(event.url)
    }
  })
  return () => {
    Linking.removeAllListeners('url')
  }
})
```

#### 添加匹配的 Munification 声明 (Android)

```xml
<activity
        android:name=".MainActivity"
        android:exported="true"
        android:launchMode="singleTask"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize">

    <!-- add the following at the end of the activity tag, after anything you have defined currently -->

    <intent-filter android:autoVerify="true"> <!-- autoVerify required for app links -->
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <!-- replace with your host, the path can change must must be reflected when running the flow -->
        <!-- the path should correspond with the routing path defined above -->
        <data android:scheme="https" android:host="<YOUR_HOST_HERE>" android:path="/auth" />
        <!-- see magic link setup below for more details -->
        <data android:scheme="https" android:host="<YOUR_HOST_HERE>" android:path="/magiclink" />
    </intent-filter>

    <!-- Optional: App Links are blocked by default on Opera and some other browsers. Add a custom scheme for that use case specifically -->
    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <!-- replace with something unique. this will only be used as a backup for Opera and some other browsers. -->
        <data android:scheme="myapp" android:host="auth" />
    </intent-filter>
</activity>
```

### 运行流程

在完成先决条件步骤后,现在可以运行一个流量. 流会以专注方式运行 `FlowView` 收到的组件 `FlowOptions`。 。 。 . 这个 `FlowOptions` 定义在运行双向流时可用的所有选项 Android and iOS. (原始内容存档于2018-09-29). 阅读组件文档以进行详细解释.

```js
import { FlowView, useHostedFlowUrl, useSession } from '@descope/react-native-sdk'

const { manageSession } = useSession()

const flowUrl = 'https://myflowUrl.com'
// If using Descope hosted flows, you can provide the flow ID directly
// const flowUrl = useHostedFlowUrl('<FLOW_ID_TO_RUN>')

<FlowView
  style={styles.fill}
  flowOptions={{
      url: flowUrl,
      androidOAuthNativeProvider: 'google',
      iosOAuthNativeProvider: 'apple',
      // any other options go here
  }}
  deepLink={deepLink} // the optional deep link we defined earlier via `useState`
  onReady={() => {
    // logic to display the flow when it's ready
  }}
  onSuccess={async (jwtResponse) => {
    try {
      await manageSession(jwtResponse)
    } catch (e) {
      // handle session management error
    }
  }}
  onError={(error: string) => {
    // handle flow errors here
  }}
/>
```

### 流量输出

流量可以通过在Descope控制台上设置流量输出来返回自定义数据. 现在, 上面有这个 `flowOutput` 字段。 对象 对于不是源源流的认证,是空的.

```js
onSuccess={async (jwtResponse) => {
  const orgId = jwtResponse.flowOutput.organizationId as string | undefined
  // ...
}}
```

## 使用 `useDescope` 财务报告和审定财务报表 `useSession` 为获取认证状态、用户细节和公用设备在组件中设置钩子

这可能有助于实施应用程序特定逻辑. 实例:

-   如果当前会话被认证, 将不同组件渲染
-   渲染用户内容
-   注销按钮

```js
import { useDescope, useSession } from '@descope/react-native-sdk'
import { useCallback } from 'react'

const App = () => {
  // NOTE - `useDescope`, `useSession`, should be used inside `AuthProvider` context,
  // and will throw an exception if this requirement is not met
  const { session } = useSession()
  const { logout } = useDescope()

  const handleLogout = useCallback(() => {
    logout()
  }, [logout])

  if (session) {
    return (
      <>
        <p>Hello {session.user.name}</p>
        <button onClick={handleLogout}>Logout</button>
      </>
    )
  }

  return <p>You are not logged in</p>
}
```

**对于更多的 SDK 使用示例参考 [文档](https://docs.descope.com/build/guides/client_sdks/)**

## 密码

密码从盒子里流出 这个 `passkey` API 允许您认证 平台验证器直接,不运行流.

密码需要 **iOS 15 (韩语)** 或者说 **机器人9** (API 28) (英语). 这不会改变最小版本 sDK支持 - 这是一个运行时间要求, 所以保持您的部署目标 `minSdkVersion` 它们的存在和用途 `isSupported()` 决定是否提供密码.

### 设置 # 1 : 配置工程

启用密码( WebAuthn) [望远镜控制台](https://app.descope.com/settings/authentication/webauthn) 并设置顶级域。 需要域 - 不同于流量, 本地 API 没有 掉回从呼叫者那里得到它,所以没有它,密码就会失效.

### 设置 # 2. 1: iOS 上的关联域

添加一个 [`webcredentials`](https://developer.apple.com/documentation/xcode/supporting-associated-domains) 匹配以上配置域的关联域权限 :

```
webcredentials:example.com
```

### 设置 2.2: Android上的数字资产链接

主办单位a [`assetlinks.json`](https://developer.android.com/training/sign-in/passkeys#add-support-dal) 上的文件,包括 `get_login_creds` 关系.

Android来源于应用程序的签名证书 `android:apk-key-hash:<sha256>`。 。 。 .

在Descope项目中登记这些证书指纹是: **选项**如果无 已配置, 任何Android来源都被接受 。 注册将密码认证限制为 建你签名,推荐生产.

请注意,这是全部或完全没有的:一旦登记了一个指纹,任何来源都会 与注册指纹不符的指纹被拒绝。 注册您携带的每个证书 :

-   这个 **调试** 证书,用于本地开发.
-   这个 **释放** (上载)证书.
-   这个 **播放应用程序签名** 证书,如果应用程序通过Google Play发布. 播放 用 Google 键控重签应用程序, 因此到达用户的证书不是您的 上传密钥 。 从游戏控制台取出 - > 设置 - > 应用完整性 - > 应用签名.

关闭 Play App 签名证书会产生一个在测试中容易丢失的失败 : 密码在本地和内部建筑中工作, 只对从 Play 安装的用户失败 存储.

### 使用量

```js
import { useDescope, useSession } from '@descope/react-native-sdk'

const descope = useDescope()
const { manageSession } = useSession()

// authenticates an existing user, or creates one if they don't exist yet
const resp = await descope.passkey.signUpOrIn('andy@example.com')
manageSession(resp.data)
```

`signUp(loginId, name)`, (中文(简体) ), `signIn(loginId)` 财务报告和审定财务报表 `add(loginId, refreshJwt)` 也可查阅.

检查 `isSupported()` 在提供密码之前, 所以无法使用密码的设备不显示 选项:

```js
if (await descope.passkey.isSupported()) {
  // show the passkey option
}
```

## 解决问题

### 修复 XCode 26+ 兼容性问题

**标准反应原生项目** - 把这个加到 `ios/Podfile` 内部 `post_install`数字 :

```ruby
post_install do |installer|
  # ...existing post_install code...

  # Workaround for fmt consteval errors with Xcode 26+
  # Remove once React Native ships fmt >= 12.1.0
  fmt_base = File.join(installer.sandbox.pod_dir('fmt'), 'include', 'fmt', 'base.h')
  if File.exist?(fmt_base)
    content = File.read(fmt_base)
    patched = content.gsub(/#  define FMT_USE_CONSTEVAL 1/, '#  define FMT_USE_CONSTEVAL 0')
    File.write(fmt_base, patched)
  end
end
```

**展览项目** - 因为博览会使 `Podfile` 每页 `prebuild`,使用配置插件。 创建 `plugins/fix-fmt-consteval.js`数字 :

```js
const { withDangerousMod } = require('expo/config-plugins')
const fs = require('fs')
const path = require('path')

module.exports = function withFixFmtConsteval(config) {
  return withDangerousMod(config, [
    'ios',
    async (config) => {
      const podfilePath = path.join(config.modRequest.platformProjectRoot, 'Podfile')
      let podfile = fs.readFileSync(podfilePath, 'utf8')
      const marker = '# Workaround for fmt consteval errors with Xcode 26+'
      if (podfile.includes(marker)) return config

      const patch = `
    ${marker}
    fmt_base = File.join(installer.sandbox.pod_dir('fmt'), 'include', 'fmt', 'base.h')
    if File.exist?(fmt_base)
      content = File.read(fmt_base)
      patched = content.gsub(/#  define FMT_USE_CONSTEVAL 1/, '#  define FMT_USE_CONSTEVAL 0')
      File.write(fmt_base, patched)
    end
`
      podfile = podfile.replace(/(post_install do \|installer\|)/, `$1\n${patch}`)
      fs.writeFileSync(podfilePath, podfile)
      return config
    },
  ])
}
```

那就登记在册 `app.json`数字 :

```json
{
  "expo": {
    "plugins": ["./plugins/fix-fmt-consteval.js"]
  }
}
```

重新运行 `expo prebuild` (或删除) `ios/` 运行 `expo run:ios`),并会应用补丁.

## 学习更多

学习更多 请看 [视角文档和 API 参考页面](https://docs.descope.com/)。 。 。 .

## 联系我们

如果您需要帮助, 您可以发送电子邮件 [瞄准镜支持](mailto:support@descope.com)

## 许可证

React Industrial的SDK号探测器在下列条件下获得使用许可: [麻省理工学院许可证协议](https://npmcn.com/package/%40descope/react-native-sdk/LICENSE)。 。 。 .

## 常见问题

### @descope/react-native-sdk 是什么？

反射的SDK望远镜

### 如何安装 @descope/react-native-sdk？

在项目目录运行 npm install @descope/react-native-sdk，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（\*）、react-native（\*）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @descope/react-native-sdk 支持 TypeScript 吗？

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

### @descope/react-native-sdk 支持 ESM 还是 CommonJS？

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

### @descope/react-native-sdk 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>= 18\.18\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @descope/react-native-sdk 可以商用吗？

@descope/react-native-sdk 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @descope/react-native-sdk 的下载量有多少？

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

### @descope/react-native-sdk 还在维护吗？

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

