ios 凭据验证_在 iOS 上使用 Google 登录服务进行身份验证

您可以将 Google 登录机制集成到您的应用中,让您的用户可使用自己的 Google 帐号进行 Firebase 身份验证。

准备工作

将 Firebase 添加到您的 iOS 项目。在您的 Podfile 中添加以下 Pod:

pod 'Firebase/Auth'

pod 'GoogleSignIn'

如果您尚未将您的应用与 Firebase 项目相关联,请在 Firebase 控制台中进行关联。

在 Firebase 控制台中启用 Google 登录机制:

在 Firebase 控制台中,打开身份验证 (Authentication) 部分。

在登录方法标签中,启用 Google 登录方法,然后点击保存。

1. 导入所需的头文件

首先,您必须将 Firebase SDK 和 Google Sign-In SDK 的头文件导入到您的应用中。

Swift

在您的应用委托中,导入以下头文件:

import Firebase

import GoogleSignIn

在您的登录视图的视图控制器中,导入以下头文件:

import Firebase

import GoogleSignIn

Objective-C

在您的应用委托中,导入以下头文件:

@import Firebase;

@import GoogleSignIn;

在您的登录视图的视图控制器中,导入以下头文件:

@import Firebase;

@import GoogleSignIn;

2. 实现 Google 登录

按下列步骤实现 Google 登录。如需详细了解如何在 iOS 设备上使用 Google 登录服务,请参阅 Google 登录开发者文档。

将自定义网址架构添加到您的 Xcode 项目中:

打开您的项目配置:在左侧的树状视图中双击项目名称。从目标部分中选择您的应用,然后选择信息标签页,并展开网址类型部分。

点击 + 按钮,并为您的倒序客户端 ID 添加一个网址架构。要找到这个值,请打开 GoogleService-Info.plist 配置文件,然后查找 REVERSED_CLIENT_ID 键。复制该键的值,并将其粘贴到配置页面上的网址架构框中。将其他字段留空。

完成上述操作后,您的配置应显示如下(但其中的值应替换为您的应用特有的值):

声明此应用委托实现了 GIDSignInDelegate 协议。

Swift在 AppDelegate.swift 中:class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {

Objective-C在 AppDelegate.h 中:@interface AppDelegate : UIResponder

在应用委托的 application:didFinishLaunchingWithOptions: 方法中,配置 FirebaseApp 对象并设置登录委托。

Swift

// Use Firebase library to configure APIs

FirebaseApp.configure()

GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID

GIDSignIn.sharedInstance().delegate = self

Objective-C

// Use Firebase library to configure APIs

[FIRApp configure];

[GIDSignIn sharedInstance].clientID = [FIRApp defaultApp].options.clientID;

[GIDSignIn sharedInstance].delegate = self;

实现您的应用委托中的 application:openURL:options: 方法。此方法应该调用 GIDSignIn 实例的 handleURL 方法,该方法将对您的应用在身份验证过程结束时收到的网址进行适当处理。

Swift

@available(iOS 9.0, *)

func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any])

-> Bool {

return GIDSignIn.sharedInstance().handle(url)

}

Objective-C

- (BOOL)application:(nonnull UIApplication *)application

openURL:(nonnull NSURL *)url

options:(nonnull NSDictionary *)options {

return [[GIDSignIn sharedInstance] handleURL:url];

}

要让您的应用在 iOS 8 及更早版本上也能运行,还需要实现已弃用的 application:openURL:sourceApplication:annotation: 方法。

Swift

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

return GIDSignIn.sharedInstance().handle(url)

}

Objective-C

- (BOOL)application:(UIApplication *)application

openURL:(NSURL *)url

sourceApplication:(NSString *)sourceApplication

annotation:(id)annotation {

return [[GIDSignIn sharedInstance] handleURL:url];

}

在应用委托中,通过定义以下方法来实现 GIDSignInDelegate 协议,以便处理登录过程:

Objective-C

- (void)signIn:(GIDSignIn *)signIn

didSignInForUser:(GIDGoogleUser *)user

withError:(NSError *)error {

// ...

if (error == nil) {

GIDAuthentication *authentication = user.authentication;

FIRAuthCredential *credential =

[FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken

accessToken:authentication.accessToken];

// ...

} else {

// ...

}

}

- (void)signIn:(GIDSignIn *)signIn

didDisconnectWithUser:(GIDGoogleUser *)user

withError:(NSError *)error {

// Perform any operations when the user disconnects from app here.

// ...

}

Swift

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {

// ...

if let error = error {

// ...

return

}

guard let authentication = user.authentication else { return }

let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,

accessToken: authentication.accessToken)

// ...

}

func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {

// Perform any operations when the user disconnects from app here.

// ...

}

在视图控制器中,重写 viewDidLoad 方法以设置 GIDSignIn 对象的演示视图控制器,并(可选)尽可能以静默方式登录。

Objective-C

[GIDSignIn sharedInstance].presentingViewController = self;

[[GIDSignIn sharedInstance] signIn];

Swift

GIDSignIn.sharedInstance()?.presentingViewController = self

GIDSignIn.sharedInstance().signIn()

将 GIDSignInButton 添加到您的 storyboard 或 XIB 文件中,或以编程方式将其实例化。要将该按钮添加到您的 storyboard 或 XIB 文件中,可添加一个视图,并将其自定义类设置为 GIDSignInButton。当您将一个 GIDSignInButton 视图添加到 storyboard 时,界面构建器中不会显示登录按钮。运行应用后才能看到登录按钮。

可选:如果要自定义该按钮,请执行以下操作:

Swift

在您的视图控制器中,将登录按钮声明为一个属性。@IBOutlet weak var signInButton: GIDSignInButton!

将该按钮关联到您刚才声明的 signInButton 属性。

通过设置 GIDSignInButton 对象的属性来自定义该按钮。

Objective-C

在您的视图控制器的头文件中,将登录按钮声明为一个属性。@property(weak, nonatomic) IBOutlet GIDSignInButton *signInButton;

将该按钮关联到您刚才声明的 signInButton 属性。

通过设置 GIDSignInButton 对象的属性来自定义该按钮。

3. 进行 Firebase 身份验证

在 signIn:didSignInForUser:withError: 方法中,从 GIDAuthentication 对象中获取一个 Google ID 令牌和一个 Google 访问令牌,然后用它们换取一个 Firebase 凭据:

Swift

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {

// ...

if let error = error {

// ...

return

}

guard let authentication = user.authentication else { return }

let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,

accessToken: authentication.accessToken)

// ...

}

Objective-C

- (void)signIn:(GIDSignIn *)signIn

didSignInForUser:(GIDGoogleUser *)user

withError:(NSError *)error {

// ...

if (error == nil) {

GIDAuthentication *authentication = user.authentication;

FIRAuthCredential *credential =

[FIRGoogleAuthProvider credentialWithIDToken:authentication.idToken

accessToken:authentication.accessToken];

// ...

} else {

// ...

}

}

最后,使用该凭据进行 Firebase 身份验证:

Swift

Auth.auth().signIn(with: credential) { (authResult, error) in

if let error = error {

let authError = error as NSError

if (isMFAEnabled && authError.code == AuthErrorCode.secondFactorRequired.rawValue) {

// The user is a multi-factor user. Second factor challenge is required.

let resolver = authError.userInfo[AuthErrorUserInfoMultiFactorResolverKey] as! MultiFactorResolver

var displayNameString = ""

for tmpFactorInfo in (resolver.hints) {

displayNameString += tmpFactorInfo.displayName ?? ""

displayNameString += " "

}

self.showTextInputPrompt(withMessage: "Select factor to sign in\n\(displayNameString)", completionBlock: { userPressedOK, displayName in

var selectedHint: PhoneMultiFactorInfo?

for tmpFactorInfo in resolver.hints {

if (displayName == tmpFactorInfo.displayName) {

selectedHint = tmpFactorInfo as? PhoneMultiFactorInfo

}

}

PhoneAuthProvider.provider().verifyPhoneNumber(with: selectedHint!, uiDelegate: nil, multiFactorSession: resolver.session) { verificationID, error in

if error != nil {

print("Multi factor start sign in failed. Error: \(error.debugDescription)")

} else {

self.showTextInputPrompt(withMessage: "Verification code for \(selectedHint?.displayName ?? "")", completionBlock: { userPressedOK, verificationCode in

let credential: PhoneAuthCredential? = PhoneAuthProvider.provider().credential(withVerificationID: verificationID!, verificationCode: verificationCode!)

let assertion: MultiFactorAssertion? = PhoneMultiFactorGenerator.assertion(with: credential!)

resolver.resolveSignIn(with: assertion!) { authResult, error in

if error != nil {

print("Multi factor finanlize sign in failed. Error: \(error.debugDescription)")

} else {

self.navigationController?.popViewController(animated: true)

}

}

})

}

}

})

} else {

self.showMessagePrompt(error.localizedDescription)

return

}

// ...

return

}

// User is signed in

// ...

}

Objective-C

[[FIRAuth auth] signInWithCredential:credential

completion:^(FIRAuthDataResult * _Nullable authResult,

NSError * _Nullable error) {

if (isMFAEnabled && error && error.code == FIRAuthErrorCodeSecondFactorRequired) {

FIRMultiFactorResolver *resolver = error.userInfo[FIRAuthErrorUserInfoMultiFactorResolverKey];

NSMutableString *displayNameString = [NSMutableString string];

for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) {

[displayNameString appendString:tmpFactorInfo.displayName];

[displayNameString appendString:@" "];

}

[self showTextInputPromptWithMessage:[NSString stringWithFormat:@"Select factor to sign in\n%@", displayNameString]

completionBlock:^(BOOL userPressedOK, NSString *_Nullable displayName) {

FIRPhoneMultiFactorInfo* selectedHint;

for (FIRMultiFactorInfo *tmpFactorInfo in resolver.hints) {

if ([displayName isEqualToString:tmpFactorInfo.displayName]) {

selectedHint = (FIRPhoneMultiFactorInfo *)tmpFactorInfo;

}

}

[FIRPhoneAuthProvider.provider

verifyPhoneNumberWithMultiFactorInfo:selectedHint

UIDelegate:nil

multiFactorSession:resolver.session

completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {

if (error) {

[self showMessagePrompt:error.localizedDescription];

} else {

[self showTextInputPromptWithMessage:[NSString stringWithFormat:@"Verification code for %@", selectedHint.displayName]

completionBlock:^(BOOL userPressedOK, NSString *_Nullable verificationCode) {

FIRPhoneAuthCredential *credential =

[[FIRPhoneAuthProvider provider] credentialWithVerificationID:verificationID

verificationCode:verificationCode];

FIRMultiFactorAssertion *assertion = [FIRPhoneMultiFactorGenerator assertionWithCredential:credential];

[resolver resolveSignInWithAssertion:assertion completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {

if (error) {

[self showMessagePrompt:error.localizedDescription];

} else {

NSLog(@"Multi factor finanlize sign in succeeded.");

}

}];

}];

}

}];

}];

}

else if (error) {

// ...

return;

}

// User successfully signed in. Get user data from the FIRUser object

if (authResult == nil) { return; }

FIRUser *user = authResult.user;

// ...

}];

后续步骤

在用户首次登录后,系统会创建一个新的用户帐号,并将其与该用户登录时使用的凭据(即用户名和密码、电话号码或者身份验证提供方信息)相关联。此新帐号存储在您的 Firebase 项目中,无论用户采用何种方式登录,您项目中的每个应用都可以使用此帐号来识别用户。

在您的应用中,您可以从 FIRUser 对象中获取用户的基本个人资料信息。请参阅管理用户。

在您的 Firebase 实时数据库和 Cloud Storage 安全规则中,您可以从 auth 变量获取已登录用户的唯一用户 ID,然后利用此 ID 来控制用户可以访问哪些数据。

您可以通过将身份验证提供方凭据关联至现有用户帐号,让用户可以使用多个身份验证提供方登录您的应用。

如需让用户退出登录,请调用 signOut:。

Swift

let firebaseAuth = Auth.auth()

do {

try firebaseAuth.signOut()

} catch let signOutError as NSError {

print ("Error signing out: %@", signOutError)

}

Objective-C

NSError *signOutError;

BOOL status = [[FIRAuth auth] signOut:&signOutError];

if (!status) {

NSLog(@"Error signing out: %@", signOutError);

return;

}

您可能还需要为所有身份验证错误添加错误处理代码。请参阅处理错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值