안녕하세요 오늘은 애플 로그인에 대해여 2번째 포스팅입니다
오늘 다룰 주제는 자동 로그인(Session)을 유지하는 방법에 대해 작성해볼려고 합니다
Apple 로그인 세션을 유지 할려면 Apple의 인증 상태를 앱 실행시 마다 체크를 해주어야 됩니다. 만료 되지 않은 세션이 있는지 검증을 해야됩니다. 사용자가 로그인을 하면 apple에서는 userIdentifier 가 발급이 됩니다, 이 값은 사용자를 식별하는데 도움이 됩니다.
이 값을 UserDefaults , Coredata 등에 저장해두고, 앱이 실행될 떄마다 이를 사용하여 세션 유효성을 검증할 수 있습니다
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
let userIdentifier = appleIDCredential.user
// userIdentifier를 UserDefaults에 저장
UserDefaults.standard.set(userIdentifier, forKey: "appleUserIdentifier")
// 로그인 성공 처리
print("Apple ID 로그인 성공, UserIdentifier: \(userIdentifier)")
}
}
로그인을 진행하고 로그인이 완료 되면 appleIDCredential.user
을 저장해줍니다.
앱이 실행될때 세션이 유효한지를 확인 하기위해서는
Appdelegate 혹은 SceneDelegate 에서 체크를 해주어야 합니다
저 같은 경우엔 SceneDelegate 에서 체크를 해줍니다
func checkAppleSignInState(completion: @escaping (Bool) -> Void) {
let appleIDProvider = ASAuthorizationAppleIDProvider()
// 저장된 사용자 ID 가져오기
if let userIdentifier = UserDefaults.standard.string(forKey: "appleUserIdentifier") {
// Apple ID 상태 확인
appleIDProvider.getCredentialState(forUserID: userIdentifier) { credentialState, error in
switch credentialState {
case .authorized:
print("Apple ID 로그인 세션 유효")
completion(true) // 로그인된 상태
case .revoked, .notFound:
print("Apple ID 로그인 세션 만료 또는 자격 없음")
completion(false) // 로그인되지 않은 상태
default:
completion(false)
}
}
} else {
// 사용자 ID가 없으면 로그인되지 않은 상태로 처리
completion(false)
}
}
UserDefaults 에서 아까 저장해둔 데이터를 불러와주고 유효성을 체크합니다
저는 여기서 의문점이 생겼습니다. appleIDCredential.user 같은 경우에는 민감한 데이터인데 UserDefaults 에 암호화 없이 저장을 해도 될까 라는 생각이 들어 찾아보니 appleIDCredential.user 는 개인정보(전화번호, 이름, 주민번호)등의 민감한 정보가 아니라 사용자 식별용 데이터입니다 그러므로 저는 Userdefaults에 저장해도 된다고 판단 하였습니다 !