Skip to content

implementing start passkey sign-in #15168

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions FirebaseAuth/Sources/Swift/Auth/Auth.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ import FirebaseCoreExtension
import UIKit
#endif

#if os(iOS) || os(tvOS) || os(macOS) || targetEnvironment(macCatalyst)
import AuthenticationServices
#endif

// Export the deprecated Objective-C defined globals and typedefs.
#if SWIFT_PACKAGE
@_exported import FirebaseAuthInternal
Expand Down Expand Up @@ -1641,6 +1645,60 @@ extension Auth: AuthInterop {
public static let authStateDidChangeNotification =
NSNotification.Name(rawValue: "FIRAuthStateDidChangeNotification")

// MARK: Passkey Implementation

#if os(iOS) || os(tvOS) || os(macOS) || targetEnvironment(macCatalyst)

/// starts sign in with passkey retrieving challenge from GCIP and create an assertion request.
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *)
public func startPasskeySignIn() async throws ->
ASAuthorizationPlatformPublicKeyCredentialAssertionRequest {
let request = StartPasskeySignInRequest(requestConfiguration: requestConfiguration)
let response = try await backend.call(with: request)
guard let challengeInData = Data(base64Encoded: response.challenge) else {
throw NSError(
domain: AuthErrorDomain,
code: AuthInternalErrorCode.RPCResponseDecodingError.rawValue,
userInfo: [NSLocalizedDescriptionKey: "Failed to decode base64 challenge from response."]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: This error message can be moved to a constant

)
}
let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(
relyingPartyIdentifier: response.rpID
)
return provider.createCredentialAssertionRequest(
challenge: challengeInData
)
}

/// finalize sign in with passkey with existing credential assertion.
/// - Parameter platformCredential The existing credential assertion created by device.
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *)
public func finalizePasskeySignIn(withPlatformCredential platformCredential: ASAuthorizationPlatformPublicKeyCredentialAssertion) async throws
-> AuthDataResult {
let credentialID = platformCredential.credentialID.base64EncodedString()
let clientDataJSON = platformCredential.rawClientDataJSON.base64EncodedString()
let authenticatorData = platformCredential.rawAuthenticatorData.base64EncodedString()
let signature = platformCredential.signature.base64EncodedString()
let userID = platformCredential.userID.base64EncodedString()
let request = FinalizePasskeySignInRequest(
credentialID: credentialID,
clientDataJSON: clientDataJSON,
authenticatorData: authenticatorData,
signature: signature,
userId: userID,
requestConfiguration: requestConfiguration
)
let response = try await backend.call(with: request)
let user = try await Auth.auth().completeSignIn(
withAccessToken: response.idToken,
accessTokenExpirationDate: nil,
refreshToken: response.refreshToken,
anonymous: false
)
return AuthDataResult(withUser: user, additionalUserInfo: nil)
}
#endif

// MARK: Internal methods

init(app: FirebaseApp,
Expand Down
1 change: 1 addition & 0 deletions FirebaseAuth/Sources/Swift/Backend/AuthBackend.swift
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,7 @@ final class AuthBackend: AuthBackendProtocol {
return AuthErrorUtils.credentialAlreadyInUseError(
message: serverDetailErrorMessage, credential: credential, email: email
)
case "INVALID_AUTHENTICATOR_RESPONSE": return AuthErrorUtils.invalidAuthenticatorResponse()
default:
if let underlyingErrors = errorDictionary["errors"] as? [[String: String]] {
for underlyingError in underlyingErrors {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/// The GCIP endpoint for finalizePasskeySignIn rpc
private let finalizePasskeySignInEndPoint = "accounts/passkeySignIn:finalize"

class FinalizePasskeySignInRequest: IdentityToolkitRequest, AuthRPCRequest {
typealias Response = FinalizePasskeySignInResponse
/// The credential ID
let credentialID: String
/// The CollectedClientData object from the authenticator.
let clientDataJSON: String
/// The AuthenticatorData from the authenticator.
let authenticatorData: String
/// The signature from the authenticator.
let signature: String
/// The user handle
let userId: String

init(credentialID: String,
clientDataJSON: String,
authenticatorData: String,
signature: String,
userId: String,
requestConfiguration: AuthRequestConfiguration) {
self.credentialID = credentialID
self.clientDataJSON = clientDataJSON
self.authenticatorData = authenticatorData
self.signature = signature
self.userId = userId
super.init(
endpoint: finalizePasskeySignInEndPoint,
requestConfiguration: requestConfiguration,
useIdentityPlatform: true
)
}

var unencodedHTTPRequestBody: [String: AnyHashable]? {
var postBody: [String: AnyHashable] = [
"authenticatorAssertionResponse": [
"credentialId": credentialID,
"authenticatorAssertionResponse": [
"clientDataJSON": clientDataJSON,
"authenticatorData": authenticatorData,
"signature": signature,
"userHandle": userId,
],
] as [String: AnyHashable],
]
if let tenantID = tenantID {
postBody["tenantId"] = tenantID
}
return postBody
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

struct FinalizePasskeySignInResponse: AuthRPCResponse {
/// The user raw access token.
let idToken: String
/// Refresh token for the authenticated user.
let refreshToken: String

init(dictionary: [String: AnyHashable]) throws {
guard
let idToken = dictionary["idToken"] as? String,
let refreshToken = dictionary["refreshToken"] as? String
else {
throw AuthErrorUtils.unexpectedResponse(deserializedResponse: dictionary)
}
self.idToken = idToken
self.refreshToken = refreshToken
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// The GCIP endpoint for startPasskeySignIn rpc
private let startPasskeySignInEndpoint = "accounts/passkeySignIn:start"

@available(iOS 15.0, macOS 12.0, tvOS 16.0, *)
class StartPasskeySignInRequest: IdentityToolkitRequest, AuthRPCRequest {
typealias Response = StartPasskeySignInResponse

init(requestConfiguration: AuthRequestConfiguration) {
super.init(
endpoint: startPasskeySignInEndpoint,
requestConfiguration: requestConfiguration,
useIdentityPlatform: true
)
}

var unencodedHTTPRequestBody: [String: AnyHashable]? {
guard let tenantID = tenantID else {
return nil
}
return ["tenantId": tenantID]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

@available(iOS 15.0, macOS 12.0, tvOS 16.0, *)
struct StartPasskeySignInResponse: AuthRPCResponse {
/// The RP ID of the FIDO Relying Party
let rpID: String
/// The FIDO challenge
let challenge: String

init(dictionary: [String: AnyHashable]) throws {
guard let options = dictionary["credentialRequestOptions"] as? [String: Any] else {
throw AuthErrorUtils.unexpectedResponse(deserializedResponse: dictionary)
}
guard let rpID = options["rpId"] as? String,
let challenge = options["challenge"] as? String else {
throw AuthErrorUtils.unexpectedResponse(deserializedResponse: dictionary)
}
self.rpID = rpID
self.challenge = challenge
}
}
4 changes: 4 additions & 0 deletions FirebaseAuth/Sources/Swift/Utilities/AuthErrorUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,10 @@ class AuthErrorUtils {
error(code: .invalidRecaptchaToken)
}

static func invalidAuthenticatorResponse() -> Error {
error(code: .invalidAuthenticatorResponse)
}

static func unauthorizedDomainError(message: String?) -> Error {
error(code: .unauthorizedDomain, message: message)
}
Expand Down
11 changes: 11 additions & 0 deletions FirebaseAuth/Sources/Swift/Utilities/AuthErrors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,10 @@ import Foundation
/// Indicates that the reCAPTCHA SDK actions class failed to create.
case recaptchaActionCreationFailed = 17210

/// the authenticator response for passkey signin or enrollment is not parseable, missing required
/// fields, or certain fields are invalid values
case invalidAuthenticatorResponse = 17211

/// Indicates an error occurred while attempting to access the keychain.
case keychainError = 17995

Expand Down Expand Up @@ -528,6 +532,8 @@ import Foundation
return kErrorSiteKeyMissing
case .recaptchaActionCreationFailed:
return kErrorRecaptchaActionCreationFailed
case .invalidAuthenticatorResponse:
return kErrorInvalidAuthenticatorResponse
}
}

Expand Down Expand Up @@ -719,6 +725,8 @@ import Foundation
return "ERROR_RECAPTCHA_SITE_KEY_MISSING"
case .recaptchaActionCreationFailed:
return "ERROR_RECAPTCHA_ACTION_CREATION_FAILED"
case .invalidAuthenticatorResponse:
return "ERROR_INVALID_AUTHENTICATOR_RESPONSE"
}
}
}
Expand Down Expand Up @@ -996,3 +1004,6 @@ private let kErrorSiteKeyMissing =
private let kErrorRecaptchaActionCreationFailed =
"The reCAPTCHA SDK action class failed to initialize. See " +
"https://cloud.google.com/recaptcha-enterprise/docs/instrument-ios-apps"

private let kErrorInvalidAuthenticatorResponse =
"During passkey enrollment and sign in, the authenticator response is not parseable, missing required fields, or certain fields are invalid values that compromise the security of the sign-in or enrollment."
Loading
Loading