Created
January 26, 2024 08:35
-
-
Save MohaElder/8741e1736d8ff5a22ce82e241052afa6 to your computer and use it in GitHub Desktop.
Login With Apple in Swift with Firebase
This file contains 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
// Created by Yasushi Oh on 1/22/24. | |
// Referenced from ChatGPT | |
//UI View with the Login button component | |
import SwiftUI | |
import AuthenticationServices | |
struct Login: View { | |
var body: some View { | |
VStack { | |
LoginWithApple() | |
.frame(width: 280, height: 45) | |
} | |
} | |
} | |
#Preview { | |
Login() | |
} |
This file contains 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
// Created by Yasushi Oh on 1/22/24. | |
// Referenced from ChatGPT and Firebase Documentation https://firebase.google.com/docs/auth/ios/apple | |
// Login button component | |
import SwiftUI | |
import AuthenticationServices | |
import FirebaseAuth | |
struct LoginWithApple: UIViewRepresentable { | |
func makeUIView(context: Context) -> ASAuthorizationAppleIDButton { | |
let button = ASAuthorizationAppleIDButton() | |
button.addTarget(context.coordinator, action: #selector(Coordinator.handleAuthorizationAppleIDButtonPress), for: .touchUpInside) | |
return button | |
} | |
func updateUIView(_ uiView: ASAuthorizationAppleIDButton, context: Context) { | |
} | |
func makeCoordinator() -> Coordinator { | |
return Coordinator() | |
} | |
} | |
class Coordinator: NSObject, ASAuthorizationControllerDelegate { | |
fileprivate var currentNonce: String? | |
@objc func handleAuthorizationAppleIDButtonPress() { | |
let nonce = UserAuth.randomNonceString() | |
currentNonce = nonce | |
let appleIDProvider = ASAuthorizationAppleIDProvider() | |
let request = appleIDProvider.createRequest() | |
request.requestedScopes = [.fullName, .email] | |
request.nonce = UserAuth.sha256(nonce) | |
let authorizationController = ASAuthorizationController(authorizationRequests: [request]) | |
authorizationController.delegate = self | |
authorizationController.performRequests() | |
} | |
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) { | |
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential { | |
guard let nonce = currentNonce else { | |
fatalError("Invalid state: A login callback was received, but no login request was sent.") | |
} | |
guard let appleIDToken = appleIDCredential.identityToken else { | |
print("Unable to fetch identity token") | |
return | |
} | |
guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else { | |
print("Unable to serialize token string from data: \(appleIDToken.debugDescription)") | |
return | |
} | |
// Initialize a Firebase credential, including the user's full name. | |
let credential = OAuthProvider.appleCredential(withIDToken: idTokenString, | |
rawNonce: nonce, | |
fullName: appleIDCredential.fullName) | |
// Sign in with Firebase. | |
Auth.auth().signIn(with: credential) { (authResult, error) in | |
if (error != nil) { | |
// Error. If error.code == .MissingOrInvalidNonce, make sure | |
// you're sending the SHA256-hashed nonce as a hex string with | |
// your request to Apple." | |
print(error?.localizedDescription ?? "Firebase cannot process the nonce") | |
return | |
} | |
// User is signed in to Firebase with Apple. | |
//Please ignore warning, debug only, will remove in the future | |
print(authResult?.user.uid); | |
} | |
} | |
} | |
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) { | |
print("Sign in with Apple errored: \(error)") | |
} | |
} | |
#Preview { | |
LoginWithApple() | |
} |
This file contains 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
// Created by Yasushi Oh on 1/22/24. | |
// Referenced from Firebase Documentation https://firebase.google.com/docs/auth/ios/apple | |
// Hash functions | |
import Foundation | |
import CryptoKit | |
import AuthenticationServices | |
public class UserAuth { | |
public static func randomNonceString(length: Int = 32) -> String { | |
precondition(length > 0) | |
var randomBytes = [UInt8](repeating: 0, count: length) | |
let errorCode = SecRandomCopyBytes(kSecRandomDefault, randomBytes.count, &randomBytes) | |
if errorCode != errSecSuccess { | |
fatalError( | |
"Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(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) | |
} | |
@available(iOS 13, *) | |
public 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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an out of the box solution for login with Apple using Firebase Auth. But it is not quite out of the box, make sure you:
FirebaseApp.configure()
insideAppDelegate.swift
. An example is:The reason that I shared this gist is because I had some troubles setting the whole thing up but the docs are not that helpful to me so I had to do lots of research. But eventually it worked out and the docs are helpful in the end ;) I would like others to benefit from my discovery since I think this kind of research for some features that should be painless to implement are causing many people bunch of time. And hey, now you have a sample! Feel free to just refer from my code :)
Common Issues that I bumped into