-
Couldn't load subscription status.
- Fork 487
feat: apple sign-in support #1278
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
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
d1f561c
feat: initial implementation of apple architecture
russellwheatley 35d55ba
chore: setup package.swift with apple package
russellwheatley 5ccebec
chore: import apple to test app
russellwheatley 7f6be55
feat: support apple sign in
russellwheatley 0cbc68e
chore: example app has apple sign in capability
russellwheatley d595a8b
fix: store pending credential to allow deletion of user
russellwheatley e92dc97
test: test the existence of apple button
russellwheatley ff554e4
fix: pass in apple scopes
russellwheatley File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
47 changes: 47 additions & 0 deletions
47
FirebaseSwiftUI/FirebaseAppleSwiftUI/Sources/Services/AccountService+Apple.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| // | ||
| // AccountService+Apple.swift | ||
| // FirebaseUI | ||
| // | ||
| // Created by Russell Wheatley on 21/10/2025. | ||
| // | ||
|
|
||
| @preconcurrency import FirebaseAuth | ||
| import FirebaseAuthSwiftUI | ||
| import Observation | ||
|
|
||
| protocol AppleOperationReauthentication { | ||
| var appleProvider: AppleProviderSwift { get } | ||
| } | ||
|
|
||
| extension AppleOperationReauthentication { | ||
| @MainActor func reauthenticate() async throws -> AuthenticationToken { | ||
| guard let user = Auth.auth().currentUser else { | ||
| throw AuthServiceError.reauthenticationRequired("No user currently signed-in") | ||
| } | ||
|
|
||
| do { | ||
| let credential = try await appleProvider.createAuthCredential() | ||
| try await user.reauthenticate(with: credential) | ||
|
|
||
| return .firebase("") | ||
| } catch { | ||
| throw AuthServiceError.signInFailed(underlying: error) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @MainActor | ||
| class AppleDeleteUserOperation: AuthenticatedOperation, | ||
| @preconcurrency AppleOperationReauthentication { | ||
| let appleProvider: AppleProviderSwift | ||
| init(appleProvider: AppleProviderSwift) { | ||
| self.appleProvider = appleProvider | ||
| } | ||
|
|
||
| func callAsFunction(on user: User) async throws { | ||
| try await callAsFunction(on: user) { | ||
| try await user.delete() | ||
| } | ||
| } | ||
| } | ||
|
|
163 changes: 163 additions & 0 deletions
163
FirebaseSwiftUI/FirebaseAppleSwiftUI/Sources/Services/AppleProviderAuthUI.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| // 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. | ||
|
|
||
| import AuthenticationServices | ||
| import CryptoKit | ||
| import FirebaseAuth | ||
| import FirebaseAuthSwiftUI | ||
| import FirebaseCore | ||
| import SwiftUI | ||
|
|
||
| // MARK: - Data Extensions | ||
|
|
||
| extension Data { | ||
| var utf8String: String? { | ||
| return String(data: self, encoding: .utf8) | ||
| } | ||
| } | ||
|
|
||
| extension ASAuthorizationAppleIDCredential { | ||
| var authorizationCodeString: String? { | ||
| return authorizationCode?.utf8String | ||
| } | ||
|
|
||
| var idTokenString: String? { | ||
| return identityToken?.utf8String | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Authenticate With Apple Dialog | ||
|
|
||
| private func authenticateWithApple( | ||
| scopes: [ASAuthorization.Scope] | ||
| ) async throws -> (ASAuthorizationAppleIDCredential, String) { | ||
| return try await AuthenticateWithAppleDialog(scopes: scopes).authenticate() | ||
| } | ||
|
|
||
| private class AuthenticateWithAppleDialog: NSObject { | ||
| private var continuation: CheckedContinuation<(ASAuthorizationAppleIDCredential, String), Error>? | ||
| private var currentNonce: String? | ||
| private let scopes: [ASAuthorization.Scope] | ||
|
|
||
| init(scopes: [ASAuthorization.Scope]) { | ||
| self.scopes = scopes | ||
| super.init() | ||
| } | ||
|
|
||
| func authenticate() async throws -> (ASAuthorizationAppleIDCredential, String) { | ||
| return try await withCheckedThrowingContinuation { continuation in | ||
| self.continuation = continuation | ||
|
|
||
| let appleIDProvider = ASAuthorizationAppleIDProvider() | ||
| let request = appleIDProvider.createRequest() | ||
| request.requestedScopes = scopes | ||
|
|
||
| do { | ||
| let nonce = try CryptoUtils.randomNonceString() | ||
| currentNonce = nonce | ||
| request.nonce = CryptoUtils.sha256(nonce) | ||
| } catch { | ||
| continuation.resume(throwing: AuthServiceError.signInFailed(underlying: error)) | ||
| return | ||
| } | ||
|
|
||
| let authorizationController = ASAuthorizationController(authorizationRequests: [request]) | ||
| authorizationController.delegate = self | ||
| authorizationController.performRequests() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| extension AuthenticateWithAppleDialog: ASAuthorizationControllerDelegate { | ||
| func authorizationController( | ||
| controller: ASAuthorizationController, | ||
| didCompleteWithAuthorization authorization: ASAuthorization | ||
| ) { | ||
| if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential { | ||
| if let nonce = currentNonce { | ||
| continuation?.resume(returning: (appleIDCredential, nonce)) | ||
| } else { | ||
| continuation?.resume( | ||
| throwing: AuthServiceError.signInFailed( | ||
| underlying: NSError( | ||
| domain: "AppleSignIn", | ||
| code: -1, | ||
| userInfo: [NSLocalizedDescriptionKey: "Missing nonce"] | ||
| ) | ||
| ) | ||
| ) | ||
| } | ||
| } else { | ||
| continuation?.resume( | ||
| throwing: AuthServiceError.invalidCredentials("Missing Apple ID credential") | ||
| ) | ||
| } | ||
| continuation = nil | ||
| } | ||
|
|
||
| func authorizationController( | ||
| controller: ASAuthorizationController, | ||
| didCompleteWithError error: Error | ||
| ) { | ||
| continuation?.resume(throwing: AuthServiceError.signInFailed(underlying: error)) | ||
| continuation = nil | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Apple Provider Swift | ||
|
|
||
| public class AppleProviderSwift: AuthProviderSwift, DeleteUserSwift { | ||
| public let scopes: [ASAuthorization.Scope] | ||
| let providerId = "apple.com" | ||
|
|
||
| public init(scopes: [ASAuthorization.Scope] = [.fullName, .email]) { | ||
| self.scopes = scopes | ||
| } | ||
|
|
||
| @MainActor public func createAuthCredential() async throws -> AuthCredential { | ||
| let (appleIDCredential, nonce) = try await authenticateWithApple(scopes: scopes) | ||
|
|
||
| guard let idTokenString = appleIDCredential.idTokenString else { | ||
| throw AuthServiceError.invalidCredentials("Unable to fetch identity token from Apple") | ||
| } | ||
|
|
||
| let credential = OAuthProvider.appleCredential( | ||
| withIDToken: idTokenString, | ||
| rawNonce: nonce, | ||
| fullName: appleIDCredential.fullName | ||
| ) | ||
|
|
||
| return credential | ||
| } | ||
|
|
||
| public func deleteUser(user: User) async throws { | ||
| let operation = AppleDeleteUserOperation(appleProvider: self) | ||
| try await operation(on: user) | ||
| } | ||
| } | ||
|
|
||
| public class AppleProviderAuthUI: AuthProviderUI { | ||
| public var provider: AuthProviderSwift | ||
|
|
||
| public init(provider: AuthProviderSwift) { | ||
| self.provider = provider | ||
| } | ||
|
|
||
| public let id: String = "apple.com" | ||
|
|
||
| @MainActor public func authButton() -> AnyView { | ||
| AnyView(SignInWithAppleButton(provider: provider)) | ||
| } | ||
| } | ||
|
|
||
32 changes: 32 additions & 0 deletions
32
FirebaseSwiftUI/FirebaseAppleSwiftUI/Sources/Services/AuthService+Apple.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| // 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. | ||
|
|
||
| // | ||
| // AuthService+Apple.swift | ||
| // FirebaseUI | ||
| // | ||
| // Created by Russell Wheatley on 21/10/2025. | ||
| // | ||
|
|
||
| import FirebaseAuthSwiftUI | ||
|
|
||
| public extension AuthService { | ||
| @discardableResult | ||
| func withAppleSignIn(_ provider: AppleProviderSwift? = nil) -> AuthService { | ||
| registerProvider(providerWithButton: AppleProviderAuthUI(provider: provider ?? | ||
| AppleProviderSwift())) | ||
| return self | ||
| } | ||
| } | ||
|
|
53 changes: 53 additions & 0 deletions
53
FirebaseSwiftUI/FirebaseAppleSwiftUI/Sources/Services/CryptoUtils.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| // 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. | ||
|
|
||
| import Foundation | ||
| import CryptoKit | ||
|
|
||
| /// Set of utility APIs for generating cryptographical artifacts. | ||
| enum CryptoUtils { | ||
| enum NonceGenerationError: Error { | ||
| case generationFailure(status: OSStatus) | ||
| } | ||
|
|
||
| static func randomNonceString(length: Int = 32) throws -> String { | ||
| precondition(length > 0) | ||
| var randomBytes = [UInt8](repeating: 0, count: length) | ||
| let errorCode = SecRandomCopyBytes(kSecRandomDefault, randomBytes.count, &randomBytes) | ||
| if errorCode != errSecSuccess { | ||
| throw NonceGenerationError.generationFailure(status: errorCode) | ||
| } | ||
|
|
||
| let charset: [Character] = | ||
| Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._") | ||
|
|
||
| let nonce = randomBytes.map { byte in | ||
| // Pick a random character from the set, wrapping around if needed. | ||
| charset[Int(byte) % charset.count] | ||
| } | ||
|
|
||
| return String(nonce) | ||
| } | ||
|
|
||
| static func sha256(_ input: String) -> String { | ||
| let inputData = Data(input.utf8) | ||
| let hashedData = SHA256.hash(data: inputData) | ||
| let hashString = hashedData.compactMap { | ||
| String(format: "%02x", $0) | ||
| }.joined() | ||
|
|
||
| return hashString | ||
| } | ||
| } | ||
|
|
54 changes: 54 additions & 0 deletions
54
FirebaseSwiftUI/FirebaseAppleSwiftUI/Sources/Views/SignInWithAppleButton.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| // 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. | ||
|
|
||
| import FirebaseAuthSwiftUI | ||
| import SwiftUI | ||
|
|
||
| /// A button for signing in with Apple | ||
| @MainActor | ||
| public struct SignInWithAppleButton { | ||
| @Environment(AuthService.self) private var authService | ||
| let provider: AuthProviderSwift | ||
| public init(provider: AuthProviderSwift) { | ||
| self.provider = provider | ||
| } | ||
| } | ||
|
|
||
| extension SignInWithAppleButton: View { | ||
| public var body: some View { | ||
| Button(action: { | ||
| Task { | ||
| try await authService.signIn(provider) | ||
| } | ||
| }) { | ||
| HStack { | ||
| Image(systemName: "apple.logo") | ||
| .resizable() | ||
| .renderingMode(.template) | ||
| .scaledToFit() | ||
| .frame(width: 24, height: 24) | ||
| .foregroundColor(.white) | ||
| Text("Sign in with Apple") | ||
| .fontWeight(.semibold) | ||
| .foregroundColor(.white) | ||
| } | ||
| .frame(maxWidth: .infinity, alignment: .leading) | ||
| .padding() | ||
| .background(Color.black) | ||
| .cornerRadius(8) | ||
| } | ||
| .accessibilityIdentifier("sign-in-with-apple-button") | ||
| } | ||
| } | ||
|
|
21 changes: 21 additions & 0 deletions
21
...ftUI/FirebaseAppleSwiftUI/Tests/FirebaseAppleSwiftUITests/FirebaseAppleSwiftUITests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| // 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. | ||
|
|
||
| @testable import FirebaseAppleSwiftUI | ||
| import Testing | ||
|
|
||
| @Test func example() async throws { | ||
| // Write your test here and use APIs like `#expect(...)` to check expected conditions. | ||
| } | ||
|
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(ASAuthorizationAppleIDCredential, String) tuple is being returned but I don't see where.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ah nevermind seen, interesting didn't think this was a way to go