iOS13 (二)苹果登录Sign In With Apple

5,293 阅读7分钟

在iOS13中,如果苹果开发者提供任何其他第三方登录,就必须提供“苹果登录”选项。也就是说,如果软件要求“微信登录”或是“QQ登录”时,必须同时提供“苹果登录”的选项给用户自行选择。根据苹果公司最新公布的指南,要求开发者在苹果终端的应用程序登录界面上,将“苹果登录”选项列在任何其他第三方登录的选项之上。苹果官方demo

准备:

手机系统版本:iOS13.0 及其以上版本;
Xcode版本:11.0 及其以上版本;
证书:创建支持苹果登录的证书 (注意:企业证书没有Sign in with apple功能);详细流程参考
Xcode-TARGETS-Signing&Capabilities中添加Sign In With Apple选项

一、创建登录按钮

官方提供了一个 ASAuthorizationAppleIDButton (继承自UIControl),使用这个来创建一个登录按钮。

let button = ASAuthorizationAppleIDButton()
button.addTarget(self, action: #selector(handleAuthAppleIDButtonPress), for: .touchUpInside)
button.center = self.view.center
self.view.addSubview(button)

这个按钮具有两种文案类型和三个样式,分别是:

@available(iOS 13.0, *)public enum ButtonType : Int {
    case signIn
    case `continue`
    public static var `default`: ASAuthorizationAppleIDButton.ButtonType { get }
}

@available(iOS 13.0, *)public enum Style : Int {
    case white
    case whiteOutline
    case black
}
  • Apple 提供的登录按钮有三种外观:白色,带有黑色轮廓线的白色和黑色。

  • 文案有两种:Sign In with Apple 和 Continue with Apple。(具体使用哪个文案,根据自身业务需求来定)

按钮宽高默认值为 {width:130, height:30}。

对于 ASAuthorizationAppleIDButton 我们能够自定义的东西比较少,比如背景色不能更改,文案只有两种可选,并且值不能修改,可以调整的只有圆角cornerRadius和size 。

let button = ASAuthorizationAppleIDButton(authorizationButtonType: ASAuthorizationAppleIDButton.ButtonType.continue,authorizationButtonStyle: ASAuthorizationAppleIDButton.Style.black)

button.bounds = CGRect.init(x: 0, y: 0, width: 80, height: 80)
button.cornerRadius = 40.0

问题:按钮显示的文字都是英文的,而且我们不可以修改文字。

解决:我们只需要添加本地化支持就可以了,此方法适用于一切系统文案,苹果已经做好了相关文字的适配,不需要自己写文案

  • Project->Info->Localizations->添加中文

二、Authorization 发起授权登录请求

/// 按下按钮->处理苹果ID认证
func handleAuthAppleIDButtonPress() {
    let request = ASAuthorizationAppleIDProvider().createRequest()
    request.requestedScopes = [.fullName, .email]

    let authController = ASAuthorizationController(authorizationRequests: [request])
    authController.delegate = self
    authController.presentationContextProvider = self
    authController.performRequests()//启动授权
}

解析:

  • ASAuthorizationAppleIDProvider 这个类比较简单,头文件中可以看出,主要用于创建一个 ASAuthorizationAppleIDRequest 以及获取对应 userID 的用户授权状态。在上面的方法中我们主要是用于创建一个 ASAuthorizationAppleIDRequest ,用户授权状态的获取后面会提到。

  • 给创建的 request 设置 requestedScopes ,这是个 ASAuthorizationScope 数组,目前只有两个值,ASAuthorizationScopeFullName 和 ASAuthorizationScopeEmail ,根据需求去设置即可。

  • 然后,创建 ASAuthorizationController ,它是管理授权请求的控制器,给其设置 delegate和 presentationContextProvider ,最后启动授权 performRequests

设置上下文

ASAuthorizationControllerPresentationContextProviding 就一个方法,主要是告诉 ASAuthorizationController 展示在哪个 window 上。

extension LoginViewController: ASAuthorizationControllerPresentationContextProviding {
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return self.view.window!
    } 
}

三、Verification 授权

用户发起授权请求后,系统就会弹出用户登录验证的页面

在用户没有同意授权之前或者取消授权之后,点击登录的时候,都会弹出上面这个界面,在这个授权页面,我们可以修改自己的用户名,以及可以选择共享我的电子邮箱或者隐藏邮件地址。这样一来,就可以达到隐藏自己真实信息的目的

授权一次后,再次点击登录按钮只需要选择继续或取消了

授权成功回调:

/// 授权成功
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
    
    /// 苹果ID凭证有效(授权方式一)
    if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
        /// 注意:第二次登录的时候不会返回所有数据,只返回了user,所以需要根据这个userIdentifier查询存储在服务器的完整用户信息
        let userIdentifier = appleIDCredential.user
        let fullName = appleIDCredential.fullName
        let email = appleIDCredential.email
        // 保存到钥匙串userIdkeychain
        do {
            try KeychainItem(service: "com.example.apple-samplecode.juice", account: "userIdentifier").saveItem(userIdentifier)
        } catch {
            print("Unable to save userIdentifier to keychain.")
        }

        // 请求服务器登录(登录成功后关闭登录页)
        if let viewController = self.presentingViewController as? ResultViewController {
            DispatchQueue.main.async {
                viewController.userIdentifierLabel.text = userIdentifier
                if let givenName = fullName?.givenName {
                    viewController.givenNameLabel.text = givenName
                }
                if let familyName = fullName?.familyName {
                    viewController.familyNameLabel.text = familyName
                }
                if let email = email {
                    viewController.emailLabel.text = email
                }
                self.dismiss(animated: true, completion: nil)
            }  
        }
    }

    /// 自动填充密码 (授权方式二:直接使用保存在钥匙串的用户名和密码授权登录) 
    else if let passwordCredential = authorization.credential as? ASPasswordCredential {
        // 用已有的钥匙串登录
        let username = passwordCredential.user
        let password = passwordCredential.password
        // 显示密码凭证提示
        DispatchQueue.main.async {
            let message = "The app has received your selected credential from the keychain. \n\n Username: \(username)\n Password: \(password)"
            let alertController = UIAlertController(title: "Keychain Credential Received",
                                                    message: message,
                                                    preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
            self.present(alertController, animated: true, completion: nil)
        } 
        // 请求服务器登录(登录成功后关闭登录页)
    }
}
        

授权失败回调:

/// 授权失败
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
    // Handle error.
    var errorMsg = ""
    switch (error) {///
    case ASAuthorizationError.canceled:
        errorMsg = "用户取消了授权请求"
        break
    case ASAuthorizationError.failed:
        errorMsg = "授权请求失败"
        break
    case ASAuthorizationError.invalidResponse:
        errorMsg = "授权请求响应无效"
        break
    case ASAuthorizationError.notHandled:
        errorMsg = "未能处理授权请求"
        break
    case ASAuthorizationError.unknown:
        errorMsg = "授权请求失败未知原因"
        break
    default:
        break
    }
    print(errorMsg)
}

当我们授权成功后,我们可以在 authorizationController:didCompleteWithAuthorization: 这个代理方法中获取到 ASAuthorizationAppleIDCredential ,通过这个可以拿到用户的 userID、email、fullName、authorizationCode、identityToken 以及 realUserStatus 等信息。

这些信息具体含义和用途:

  • User ID: Unique, stable, team-scoped user ID,苹果用户唯一标识符,该值在同一个开发者账号下的所有 App 下是一样的,开发者可以用该唯一标识符与自己后台系统的账号体系绑定起来。

  • Verification data: Identity token, code,验证数据,用于传给开发者后台服务器,然后开发者服务器再向苹果的身份验证服务端验证本次授权登录请求数据的有效性和真实性,详见 Sign In with Apple REST API。如果验证成功,可以根据 userIdentifier 判断账号是否已存在,若存在,则返回自己账号系统的登录态,若不存在,则创建一个新的账号,并返回对应的登录态给 App。

  • Account information: Name, verified email,苹果用户信息,包括全名、邮箱等。

  • Real user indicator: High confidence indicator that likely real user,用于判断当前登录的苹果账号是否是一个真实用户,取值有:unsupported、unknown、likelyReal。

注意:第二次登录成功后不会返回所有数据,只返回了user,所以需要根据这个userIdentifier查询存储在服务器的详细用户信息

四、Handling Changes

通过上面的步骤一个完整的授权,已经完成。但是,我们还需要处理一些 特殊情况。

  • 用户终止 App 中使用 Sign in with Apple 功能

  • 用户在设置里注销了 AppleId

这些情况下,App 需要获取到这些状态,然后做退出登录操作,或者重新登录。

我们需要在 App 启动的时候,通过 getCredentialState:completion: 来获取当前用户的授权状态。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    if (@available(iOS 13.0, *)) {
        NSString *userIdentifier = 钥匙串中取出的 userIdentifier;
        if (userIdentifier) {
            ASAuthorizationAppleIDProvider *appleIDProvider = [ASAuthorizationAppleIDProvider new];
            [appleIDProvider getCredentialStateForUserID:userIdentifier
                                              completion:^(ASAuthorizationAppleIDProviderCredentialState credentialState,
                                                           NSError * _Nullable error)
            {
                switch (credentialState) {
                    case ASAuthorizationAppleIDProviderCredentialAuthorized:
                        // The Apple ID credential is valid
                        break;
                    case ASAuthorizationAppleIDProviderCredentialRevoked:
                        // Apple ID Credential revoked, handle unlink
                        break;
                    case ASAuthorizationAppleIDProviderCredentialNotFound:
                        // Credential not found, show login UI
                        break;
                }  
            }];  
        } 
    }
    return YES;
}

ASAuthorizationAppleIDProviderCredentialState 解析如下:

  • ASAuthorizationAppleIDProviderCredentialAuthorized 授权状态有效;

  • ASAuthorizationAppleIDProviderCredentialRevoked 上次使用苹果账号登录的凭据已被移除,需解除绑定并重新引导用户使用苹果登录;

  • ASAuthorizationAppleIDProviderCredentialNotFound 未登录授权,直接弹出登录页面,引导用户登录。

另外,在 App 使用过程中,你还可以通过通知方法来监听 revoked 状态,可以添加 ASAuthorizationAppleIDProviderCredentialRevokedNotification 这个通知,收到这个通知的时候,我们可以:

  • Sign user out on this device

  • Guide to sign in again

具体怎么添加和处理,可以根据业务需求来决定。

- (void)observeAppleSignInState{
    if (@available(iOS 13.0, *)) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleSignInWithAppleStateChanged:)
                                                     name:ASAuthorizationAppleIDProviderCredentialRevokedNotification
                                                   object:nil];
    } }

- (void)handleSignInWithAppleStateChanged:(NSNotification *)notification {
    // Sign the user out, optionally guide them to sign in again
    NSLog(@"%@", notification.userInfo);
}

.

参考:

苹果登录
iOS13苹果登录的后台验证token(JAVA)

如发现遗漏或者错误,请在下方评论区留言。