Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sample app for passkey #12658

Merged
merged 3 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
objects = {

/* Begin PBXBuildFile section */
0274FD322BB5DCF000DE5140 /* MainViewController+Passkey.m in Sources */ = {isa = PBXBuildFile; fileRef = 0274FD312BB5DCF000DE5140 /* MainViewController+Passkey.m */; };
400283EA23EA254B0006A298 /* MainViewController+MultiFactor.m in Sources */ = {isa = PBXBuildFile; fileRef = 400283E923EA254A0006A298 /* MainViewController+MultiFactor.m */; };
DE1865AC245B879B00F8AD70 /* TestsBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE1865AB245B879B00F8AD70 /* TestsBase.swift */; };
DE1865AE245B8A1400F8AD70 /* AnonymousTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE1865AD245B8A1400F8AD70 /* AnonymousTests.swift */; };
Expand Down Expand Up @@ -85,6 +86,8 @@
/* End PBXContainerItemProxy section */

/* Begin PBXFileReference section */
0274FD302BB5DCF000DE5140 /* MainViewController+Passkey.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "MainViewController+Passkey.h"; sourceTree = "<group>"; };
0274FD312BB5DCF000DE5140 /* MainViewController+Passkey.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "MainViewController+Passkey.m"; sourceTree = "<group>"; };
400283E823EA254A0006A298 /* MainViewController+MultiFactor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "MainViewController+MultiFactor.h"; sourceTree = "<group>"; };
400283E923EA254A0006A298 /* MainViewController+MultiFactor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "MainViewController+MultiFactor.m"; sourceTree = "<group>"; };
DE1865AB245B879B00F8AD70 /* TestsBase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestsBase.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -277,6 +280,8 @@
DE800B4222A2F8AF00AC9A23 /* MainViewController+GameCenter.h */,
DE800B1922A2F8AF00AC9A23 /* MainViewController+GameCenter.m */,
DE800B2122A2F8AF00AC9A23 /* MainViewController+Google.h */,
0274FD302BB5DCF000DE5140 /* MainViewController+Passkey.h */,
0274FD312BB5DCF000DE5140 /* MainViewController+Passkey.m */,
DE800B3922A2F8AF00AC9A23 /* MainViewController+Google.m */,
DE800B3022A2F8AF00AC9A23 /* MainViewController+Internal.h */,
400283E823EA254A0006A298 /* MainViewController+MultiFactor.h */,
Expand Down Expand Up @@ -534,6 +539,7 @@
DE800B5A22A2F8AF00AC9A23 /* MainViewController+App.m in Sources */,
DE800B6222A2F8AF00AC9A23 /* CustomTokenDataEntryViewController.m in Sources */,
DE800B6122A2F8AF00AC9A23 /* ApplicationDelegate.m in Sources */,
0274FD322BB5DCF000DE5140 /* MainViewController+Passkey.m in Sources */,
DE800B4A22A2F8AF00AC9A23 /* GoogleAuthProvider.m in Sources */,
DE800B5B22A2F8AF00AC9A23 /* MainViewController+OAuth.m in Sources */,
DE800B6022A2F8AF00AC9A23 /* FacebookAuthProvider.m in Sources */,
Expand Down
107 changes: 65 additions & 42 deletions FirebaseAuth/Tests/Sample/Sample/MainViewController+OAuth.m
Original file line number Diff line number Diff line change
Expand Up @@ -434,53 +434,76 @@ - (void)revokeAppleTokenAndDeleteUser {
}

- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {
ASAuthorizationAppleIDCredential* appleIDCredential = authorization.credential;
NSString *IDToken = [NSString stringWithUTF8String:[appleIDCredential.identityToken bytes]];
FIROAuthCredential *credential =
[FIROAuthProvider appleCredentialWithIDToken:IDToken
rawNonce:self.appleRawNonce
fullName:appleIDCredential.fullName];

if ([appleIDCredential.state isEqualToString:@"signIn"]) {
[FIRAuth.auth signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
if (!error) {
NSLog(@"%@", authResult.description);
} else {
NSLog(@"%@", error.description);
}
}];
} else if ([appleIDCredential.state isEqualToString:@"link"]) {
[FIRAuth.auth.currentUser linkWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
if (!error) {
NSLog(@"%@", authResult.description);
} else {
NSLog(@"%@", error.description);
}
}];
} else if ([appleIDCredential.state isEqualToString:@"reauth"]) {
[FIRAuth.auth.currentUser reauthenticateWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
if (!error) {
NSLog(@"%@", authResult.description);
} else {
NSLog(@"%@", error.description);
}
}];
} else if ([appleIDCredential.state isEqualToString:@"revokeAppleTokenAndDeleteUser"]) {
NSString *code = [[NSString alloc] initWithData:appleIDCredential.authorizationCode encoding:NSUTF8StringEncoding];
if (@available(iOS 16.0, *)) {
if ([authorization.credential isKindOfClass: [ASAuthorizationPlatformPublicKeyCredentialRegistration class]]) {
ASAuthorizationPlatformPublicKeyCredentialRegistration *platformCredential = (ASAuthorizationPlatformPublicKeyCredentialRegistration*) authorization.credential;

FIRUser *user = FIRAuth.auth.currentUser;
[FIRAuth.auth revokeTokenWithAuthorizationCode:code completion:^(NSError * _Nullable error) {
[user finalizePasskeyEnrollmentWithPlatformCredential:platformCredential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
[self log:[NSString stringWithFormat:@"Passkey Enrollment succeed with uid: %@", authResult.user.uid] ];
[self showTypicalUIForUserUpdateResultsWithTitle:@"Enrollment with passkey" error:error];
}];

} else if ([authorization.credential isKindOfClass: [ASAuthorizationPlatformPublicKeyCredentialAssertion class]]) {
ASAuthorizationPlatformPublicKeyCredentialAssertion *platformCredential = (ASAuthorizationPlatformPublicKeyCredentialAssertion*) authorization.credential;
[[AppManager auth] finalizePasskeySignInWithPlatformCredential:platformCredential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
[self log:[NSString stringWithFormat:@"Passkey sign-in succeed with uid: %@", authResult.user.uid]];
[self showTypicalUIForUserUpdateResultsWithTitle:@"Sign in with passkey" error:error];

}];
}
} else if ([authorization.credential isKindOfClass: [ASAuthorizationAppleIDCredential class]]) {
ASAuthorizationAppleIDCredential* appleIDCredential = authorization.credential;
NSString *IDToken = [NSString stringWithUTF8String:[appleIDCredential.identityToken bytes]];
FIROAuthCredential *credential =
[FIROAuthProvider appleCredentialWithIDToken:IDToken
rawNonce:self.appleRawNonce
fullName:appleIDCredential.fullName];

if ([appleIDCredential.state isEqualToString:@"signIn"]) {
[FIRAuth.auth signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
if (!error) {
// Token revocation succeeded then delete user again.
[user deleteWithCompletion:^(NSError *_Nullable error) {
if (error) {
[self logFailure:@"delete account failed" error:error];
}
[self showTypicalUIForUserUpdateResultsWithTitle:@"Delete User" error:error];
}];
NSLog(@"%@", authResult.description);
} else {
NSLog(@"%@", error.description);
}
}];
}];
} else if ([appleIDCredential.state isEqualToString:@"link"]) {
[FIRAuth.auth.currentUser linkWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
if (!error) {
NSLog(@"%@", authResult.description);
} else {
NSLog(@"%@", error.description);
}
}];
} else if ([appleIDCredential.state isEqualToString:@"reauth"]) {
[FIRAuth.auth.currentUser reauthenticateWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
if (!error) {
NSLog(@"%@", authResult.description);
} else {
NSLog(@"%@", error.description);
}
}];
} else if ([appleIDCredential.state isEqualToString:@"revokeAppleTokenAndDeleteUser"]) {
NSString *code = [[NSString alloc] initWithData:appleIDCredential.authorizationCode encoding:NSUTF8StringEncoding];
FIRUser *user = FIRAuth.auth.currentUser;
[FIRAuth.auth revokeTokenWithAuthorizationCode:code completion:^(NSError * _Nullable error) {
if (!error) {
// Token revocation succeeded then delete user again.
[user deleteWithCompletion:^(NSError *_Nullable error) {
if (error) {
[self logFailure:@"delete account failed" error:error];
}
[self showTypicalUIForUserUpdateResultsWithTitle:@"Delete User" error:error];
}];
} else {
NSLog(@"%@", error.description);
}
}];
}
} else {
// More supported credential type can be added here.
[self log:@"credential type not found or OS version too low."];
}
}

Expand Down
31 changes: 31 additions & 0 deletions FirebaseAuth/Tests/Sample/Sample/MainViewController+Passkey.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#import <Foundation/Foundation.h>

#import "MainViewController.h"

#import "StaticContentTableViewManager.h"

NS_ASSUME_NONNULL_BEGIN

@interface MainViewController (Passkey)

- (StaticContentTableViewSection *)passkeySection;

@end

NS_ASSUME_NONNULL_END
118 changes: 118 additions & 0 deletions FirebaseAuth/Tests/Sample/Sample/MainViewController+Passkey.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "MainViewController+Passkey.h"
#import "AppManager.h"
#import "MainViewController+Internal.h"
#import <AuthenticationServices/AuthenticationServices.h>


NS_ASSUME_NONNULL_BEGIN
@interface MainViewController () <ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>
@end

@implementation MainViewController (Passkey)

- (StaticContentTableViewSection *)passkeySection {
__weak typeof(self) weakSelf = self;
return [StaticContentTableViewSection sectionWithTitle:@"Passkey" cells:@[
[StaticContentTableViewCell cellWithTitle:@"Sign Up With Passkey"
action:^{ [weakSelf passkeySignUp]; }],
[StaticContentTableViewCell cellWithTitle:@"Sign In With Passkey"
action:^{ [weakSelf passkeySignIn]; }],
[StaticContentTableViewCell cellWithTitle:@"Enroll with Passkey"
action:^{ [weakSelf passkeyEnroll]; }],
[StaticContentTableViewCell cellWithTitle:@"Unenroll with Passkey"
action:^{ [weakSelf passkeyUnenroll]; }],
]];
}

- (void)passkeySignUp {
// sign in anoymously
[[AppManager auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult *_Nullable result,
NSError *_Nullable error) {
if (error) {
[self logFailure:@"sign-in anonymously failed" error:error];
} else {
[self logSuccess:@"sign-in anonymously succeeded."];
[self log:[NSString stringWithFormat:@"User ID : %@", result.user.uid]];
[self passkeyEnroll];
}
}];
}

- (void)passkeyEnroll {
FIRUser *user = FIRAuth.auth.currentUser;
if (!user) {
[self logFailure:@"Please sign in first." error:nil];
return;
}
[self showTextInputPromptWithMessage:@"passkey name"
keyboardType:UIKeyboardTypeEmailAddress
completionBlock:^(BOOL userPressedOK, NSString *_Nullable passkeyName) {
if (@available(iOS 16.0, macOS 12.0, tvOS 16.0, *)) {
[user startPasskeyEnrollmentWithName:passkeyName completion:^(ASAuthorizationPlatformPublicKeyCredentialRegistrationRequest * _Nullable request, NSError * _Nullable error) {
if (request) {
ASAuthorizationController *controller = [[ASAuthorizationController alloc] initWithAuthorizationRequests: [NSMutableArray arrayWithObject:request]];
controller.delegate = self;
controller.presentationContextProvider = self;
[controller performRequests];
} else if (error) {
[self logFailure:@"Passkey enrollment failed" error:error];
}
}];
} else {
[self log:@"OS version is not supported for this action."];
}
}];

}

- (void)passkeySignIn {
if (@available(iOS 16.0, macOS 12.0, tvOS 16.0, *)) {
[[AppManager auth] startPasskeySignInWithCompletion:^(ASAuthorizationPlatformPublicKeyCredentialAssertionRequest * _Nullable request, NSError * _Nullable error) {
if (request) {
ASAuthorizationController *controller = [[ASAuthorizationController alloc] initWithAuthorizationRequests: [NSMutableArray arrayWithObject:request]];
controller.delegate = self;
controller.presentationContextProvider = self;
[controller performRequestsWithOptions:ASAuthorizationControllerRequestOptionPreferImmediatelyAvailableCredentials];
}
}];
} else {
[self log:@"OS version is not supported for this action."];
}
}

- (void)passkeyUnenroll {
FIRUser *user = FIRAuth.auth.currentUser;
if (!user) {
[self logFailure:@"Please sign in first." error:nil];
return;
}
[self showTextInputPromptWithMessage:@"passkey credential ID"
completionBlock:^(BOOL userPressedOK, NSString *_Nullable credentialID) {
[user unenrollPasskeyWithCredentialID:credentialID completion:^(NSError * _Nullable error) {
if (error) {
[self logFailure:[NSString stringWithFormat:@"Withdraw passkey with credential ID: %@ failed", credentialID] error:error];
} else {
[self logSuccess:[NSString stringWithFormat:@"Withdraw passkey with credential ID: %@ succeed", credentialID]];
}
}];
}];
}

@end

NS_ASSUME_NONNULL_END
10 changes: 9 additions & 1 deletion FirebaseAuth/Tests/Sample/Sample/MainViewController.m
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
#import "UIViewController+Alerts.h"
#import "UserInfoViewController.h"
#import "UserTableViewCell.h"

#import "MainViewController+Passkey.h"
#import <AuthenticationServices/AuthenticationServices.h>
NS_ASSUME_NONNULL_BEGIN

static NSString *const kSectionTitleSettings = @"Settings";
Expand Down Expand Up @@ -252,6 +253,8 @@ - (void)updateTable {
[weakSelf oobSection],
// Auto Tests
[weakSelf autoTestsSection],
// Passkey
Xiaoshouzi-gh marked this conversation as resolved.
Show resolved Hide resolved
[weakSelf passkeySection],
]];
}

Expand Down Expand Up @@ -638,6 +641,11 @@ - (IBAction)copyConsole:(id)sender {
pasteboard.string = _consoleString ?: @"";
}

- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){

Xiaoshouzi-gh marked this conversation as resolved.
Show resolved Hide resolved
return self.view.window;
}

@end

NS_ASSUME_NONNULL_END
15 changes: 15 additions & 0 deletions FirebaseAuth/Tests/Sample/Sample/UserInfoViewController.m
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#import "UserInfoViewController.h"

#import <FirebaseAuth/FIRUser.h>
#import <FirebaseAuth/FIRPasskeyInfo.h>
#import <FirebaseAuth/FIRUserInfo.h>
#import <FirebaseAuth/FIRUserMetadata.h>
#import "StaticContentTableViewManager.h"
Expand Down Expand Up @@ -74,6 +75,8 @@ - (void)loadTableView {
value:stringWithBool(_user.emailVerified)],
[StaticContentTableViewCell cellWithTitle:@"refresh token" value:_user.refreshToken],
[StaticContentTableViewCell cellWithTitle:@"multi factor" value:[self multiFactorString]],
[StaticContentTableViewCell cellWithTitle:@"passkeys" value:[self passkeysString]],

]]
] mutableCopy];
[sections addObject:[self sectionWithUserInfo:_user]];
Expand Down Expand Up @@ -108,4 +111,16 @@ - (NSString *)multiFactorString {
return string;
}

- (NSString *)passkeysString {
NSMutableString *string = [NSMutableString string];

for (FIRPasskeyInfo *info in _user.enrolledPasskeys) {
[string appendString:info.name];
[string appendString:@" - "];
[string appendString:info.credentialID];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add separators between the passkey strings?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a space following MFA

}

return string;
}

@end
Loading