Vapor - 使用 Apple 登录

用于简化 Vapor 项目中“使用 Apple 登录”功能的实用工具。

设置

像这样链接到您的项目

dependencies: [
    ...
    .package(url: "https://github.com/mpdifran/vapor-sign-in-with-apple.git", from: "1.0.0"),
],
targets: [
    .executableTarget(
        name: "App",
        dependencies: [
            ...
            .product(name: "SignInWithApple", package: "vapor-sign-in-with-apple"),
        ]
    )
],

创建私钥

使用 Apple 提供的 JWT 的名称和内容创建一个 ApplePrivateKey。在开发者门户网站此处注册一个新密钥。

let siwaJWKID = "12345ABCDE" // Example key name
let siwaPrivateKey = "<contents of file as String>" // Store this in an environment variable, do not check into source control.

let privateKey = try ApplePrivateKey(
    kid: JWKIdentifier(string: siwaJWKId),
    privateKey: siwaPrivateKey
)

令牌生成

使用以下方法从 Apple 的服务器生成刷新令牌和访问令牌。有关此过程的 Apple 文档可以在此处找到。

let details = AppleTokenGenerationDetails(
    teamIdentifier: 123456, // Your Apple Team ID.
    appIdentifier: com.example.app, // Application Bundle ID.
    identityToken: "ABCDEF", // Identity Token generated by Sign in with Apple on the client.
    authorizationCode: "1234", // Authorization code generated by Sign in with Apple on the client.
    privateKey: privateKey // See above for generation details.
)
let tokenResponse = try await request.signInWithApple.generateAppleTokens(details: details)

// Store tokens

令牌验证

使用以下方法验证通过上述方法获得的现有刷新令牌。有关此过程的 Apple 文档可以在此处找到。

let details = AppleTokenValidationDetails(
    teamIdentifier: 123456, // Your Apple Team ID.
    appIdentifier: com.example.app, // Application Bundle ID.
    identityToken: "ABCDEF", // Identity Token generated by Sign in with Apple on the client.
    refreshToken: "1A2B3C", // Refresh token stored from previous call to `generateAppleTokens(details:)`.
    privateKey: privateKey // See above for generation details.
)
let tokenResponse = try await request.signInWithApple.validateAppleTokens(details: details)

// Store tokens