Single Sign-On in iOS 애플, 구글

rbw·2023년 9월 20일
0

TIL

목록 보기
91/97

https://medium.com/@greenSyntax/single-sign-on-on-ios-cc0af3d03aaa 요거 보고 번역 정리 한 글 자세한건 저 link gogo

SSO란 1회 사용자 인증으로 다수의 앱 및 웹에 대한 사용자 로그인을 허용하는 인증 솔루션입니다. - Amazon

흐름도

전제조건

파이어베이스를 프로젝트에 적용해야합니다. 그리고 Authenticaition에 Google, Apple을 추가해줌니다. 그 후에 구글 230로그인을 위해 프로젝트에 URL Scheme을 추가해줘야하는데 구글 서비스 plist에 있는 REVERSED_CLIENT_ID를 추가해줍니다.

Firebase Authentication

페북, 구글, 애플, 트위터, 깃헙 등 다양한 소셜 계정에 대한 SSO를 달성하는데 동무이 되는 Firebase 인증을 사용할것입니다. 추가해야할 패키지는 아래와 같습니다.

pod 'FirebaseAnalytics'
pod 'FirebaseAuth'
pod 'Firebase'
pod 'GoogleSignIn'

이제 인증 모듈이 프로젝트에 추가되었고, 인증 레이어를 구현할 준비가 되었습니다. 여기서는 구글과 애플의 인증 계층의 통신에 델리게이트 패턴을 사용함니다

struct AppUser {
    var token: String
    var name: String
    var email: String
    var userId: String
    var imagePath: URL?
}

protocol SocialAuthenticationDelegate: AnyObject {
    func onAuthenticationSuccess(_ user: AppUser)
    func onAuthenticationError(_ error: Error)
}

Google Authentication

구글 인증에서는 파이어베이스 ClientID가 필요합니다.

class GoogleAuthentication {
    weak var delegate: SocialAuthenticationDelegate?
    
    func signIn(_ vc: UIViewController, delegate: SocialAuthenticationDelegate) {
        guard let clientID = FirebaseApp.app()?.options.clientID else { return }
        self.delegate = delegate
        
        let config = GIDConfiguration(clientID: clientID)
        GIDSignIn.sharedInstance.configuration = config
        GIDSignIn.sharedInstance.signIn(withPresenting: vc) { [unowned self] user, error in
            
            if let error = error {
                self.delegate?.onAuthenticationError(AppError.custom(error.localizedDescription))
                return
            }
            
            guard let token = user?.user.accessToken, let idToken = user?.user.idToken else { return }
            let credential = GoogleAuthProvider.credential(withIDToken: idToken.tokenString, accessToken: token.tokenString)
            Auth.auth().signIn(with: credential) { (auth, error) in
                if let error = error {
                    debugPrint("Auth Error: \(error.localizedDescription)")
                    self.delegate?.onAuthenticationError(AppError.custom(error.localizedDescription))
                } else {
                    self.delegate?.onAuthenticationSuccess(AppUser(token: auth?.user.providerID ?? "", name: auth?.user.displayName ?? "",
                     email: auth?.user.email ?? "", userId: auth?.user.uid ?? "", imagePath: auth?.user.photoURL))
                }
            }
        }
    }
}

그리고 이 친구는 뷰 모델에서 부른다고 했으니까 뷰 모델과 뷰 컨트롤러의 코드는 아래와 같슴니다. Delegate 패턴을 사용하기 때문에 채택을 한 후 구현부를 여기 작성해줌니다. 그리고 프로퍼티로 클로저를 만들어서 처리를 하고 있는 모습이네요.

// VM
class AuthenticationViewModel: AuthenticationViewModelType {
    
    private var google: GoogleAuthentication
    
    var handlerAuthenticationSuccessfull: ((_ user: AppUser) -> Void)?
    var handlerAuthenticationFailure: ((_ error: AppError) -> Void)?
    
    init(_ google: GoogleAuthentication) {
        self.google = google
    }
    
    func initializeGoogleLogin(_ vc: UIViewController) {
        google.signIn(vc, delegate: self)
    }
    
}

extension AuthenticationViewModel: SocialAuthenticationDelegate {
    func onAuthenticationSuccess(_ user: AppUser) {
        self.handlerAuthenticationSuccessfull?(user)
    }
    
    func onAuthenticationError(_ error: Error) {
        self.handlerAuthenticationFailure?(.error(error))
    }
}

// VC에서는 이렇게 호출만 하면 됩니당
@IBAction func actionButtonGoogle(_ sender: Any) {
     viewModel.initializeGoogleLogin(self)
}

Apple Authentication

애플 인증도 구글 인증과 거의 유사합니다. 다만 보일러 플레이트 코드가 좀 많긴 합니다 이 부분은 이 글 맨 위의 작성한 링크를 들어가서 확인해주시길 바람니다..! 파이어베이스 공식 문서에도 있슴니다

뷰 모델에 구글 인증에서 했던 것처럼 initialAppleLogin() 함수를 추가해주어서 애플 로그인 플로우를 수행하면 됩니다. 마찬가지로 뷰 컨트롤러에서도 위 함수를 수행하게끔 해주면 끗임니다 !

주의점

주의해야할 문제들은 아래와 같슴니다.

  • 파이어베이스가 성공적으로 구성되지 않았다면, 구글 인증 초기화 전에 파이어베이스를 먼저 초기화해야 합니다. 가장 좋은 방법은 앱 딜리게이트에서 didFinsh 부분에서 파이어베이스를 초기화하는 것입니다.
  • 앱의 URL 스키마에 제대로 된 값을 입력해야 합니다. Google Service pllist에 있는 REVERSED_CLIENT_ID를 확인하세요
  • 파이어베이스 콘솔에서 파이어베이스 인증의 구글 로그인이 활성화되어 있는지 확인해야합니다. (애플 인증도 마찬가지!)
profile
hi there 👋

0개의 댓글