---
title: "sdk/macos"
description: "适用于 macOS 的 Swift SDK，使用 ASWebAuthenticationSession、PKCE S256 授权码流程和 Keychain token 存储。与 sdk/ios 共享实现模式。"
locale: "zh-Hans"
---

> Documentation Index
> Fetch the locale documentation index at: https://xid.dev/zh-hans/llms.txt
> Use this file to discover all available pages before exploring further.

# sdk/macos

## 状态

包状态为 **已实现 · 本地已验证**。单元测试（22 个通过）在 macOS 上运行。Keychain 访问和完整 ASWebAuthenticationSession OAuth callback 流程需要运行中的 XID 实例进行 L4 验证。IdP 往返验证待人工核实。本页面记录已实现的行为，不代表生产就绪声明。

## 要求

- macOS 13+
- Swift 5.9+ 和 Xcode 15+
- 无第三方依赖——使用 Apple 系统框架（AuthenticationServices、CryptoKit、Security）

## 安装

通过 Package.swift 中的 Swift Package Manager 添加：

```swift
// Package.swift
dependencies: [
.package(url: "https://github.com/StringKe/xid", from: "0.1.0"),
],
targets: [
.target(name: "YourApp", dependencies: [.product(name: "Xid", package: "xid")]),
]
```

## 快速开始

```swift
import Xid

let client = XidClient()

// 1. Configure
client.configure(XidOptions(
issuer: URL(string: "https://xid.dev")!,
clientId: "your_client_id",
redirectUri: "yourapp://callback"
))

// 2. Sign in (opens ASWebAuthenticationSession)
let session = try await client.signIn()

// 3. Get a valid access token (auto-refresh)
let token = try await client.getAccessToken()

// 4. Get current session
let current = try await client.getSession()

// 5. Sign out
try await client.signOut()
```

## 核心 API

| 方式 | 描述 |
| --- | --- |
| `configure(_ options:)` | 设置 issuer、clientId、redirectUri 和 scopes。在所有其他方法之前调用。 |
| `signIn() async throws -> XidSession` | 启动 ASWebAuthenticationSession，完成 PKCE S256 授权码流程，将 token 持久化到 Keychain，并返回会话。 |
| `handleRedirect(_ url:) async throws -> XidSession` | 处理来自外部来源的重定向 URL 并用 code 换取 token。 |
| `getSession() async throws -> XidSession?` | 返回存储的会话，接近过期时自动轮换 refresh token。 |
| `getAccessToken() async throws -> String` | 返回有效的访问令牌字符串，如需刷新则自动刷新。 |
| `signOut() async throws` | 清除 Keychain token 并吊销本地会话。 |

## 与 sdk/ios 的关系

macOS SDK 与 sdk/ios 共享相同的 Swift 实现模式——ASWebAuthenticationSession 用于浏览器授权，CryptoKit 用于 PKCE S256，Keychain 用于 token 存储。两个包面向不同的 Apple 平台最低版本要求，分别维护以支持各平台专有的权限配置。

## 安全

- 公共客户端——不存储或传输客户端密钥。
- 仅 PKCE S256。服务器拒绝 plain challenge 方式。
- 每次请求生成 OAuth state；在重定向时验证以防 CSRF。
- Token 存储在仅限设备访问的 Keychain 中，不同步到 iCloud Keychain。

## 已知限制

- 基于 JWKS 的 ES256/RS256 ID token 验签和 end\_session 登出已实现并完成本地测试。真实 macOS Keychain 和 IdP 往返验证前仍不具备 L4 支持。
- 与 sdk/ios 共享 Swift 核心提取已在计划中，但尚未完成——每个包携带自己的实现副本。

Source: https://xid.dev/zh-hans/sdks/macos/index.mdx
