Capacitor sign in with apple is not working - ios

I am using Capacitor sign in with apple to login with Apple, this is my code:
registerApple(apple: string) {
SignInWithApple.authorize().then(resp => {
this.loginSocial(resp);
console.log("respuesta", resp.response);
if (this.error === true) {
this.activateTabMenu(true);
this.navCtrl.navigateRoot("/home");
} else {
this.register(resp.response, resp.response.user, null, null);
this.user.socialType = apple;
this.viewMode = "view1";
this.progressValue = 0.3;
this.dataDepTp();
}
}).catch((err) => console.log(err));
}
the thing is that when I test it it doesn't work, the Apple GUI doesn't open, and the xcode console prints the next message:
[log] - {"code":"UNIMPLEMENTED"}
I also already enable the Sign In with Apple in xcode and apple developers
what can I do?

Run on physical device or on macOS, iOS has a few issues with this plugin - https://github.com/capacitor-community/apple-sign-in/issues/23
The following example is Capacitor 3/4 related
Signin with apple requires an options field with a nonce.
The example below uses firebase and npm sha.js
Have a look at the https://github.com/capacitor-community/apple-sign-in docs
Also, the Firebase Apple Sign-in Setup guide explains the apple email relay config - https://firebase.google.com/docs/auth/ios/apple?authuser=0&hl=en'
async loginApple() {
if (this.platform.is('capacitor')) {
const rawNonce = 'any random string will do here';
const nonce = shajs('sha256').update(rawNonce).digest('hex');
const options: SignInWithAppleOptions = {
clientId: 'com.example.app',
redirectURI: 'https://your-app-name.firebaseapp.com/__/auth/handler',
scopes: 'email name',
state: '123456',
nonce,
};
try {
const { response } = await SignInWithApple.authorize(options);
console.log('app:auth: loginApple response - ', response);
}
}
}

Related

Supabase Auth - redirectTo not working for OAuth

I am switching from Flutter to Supabase and am running into an issue with Authentication. Although I can successfully launch the URL with the correct redirect value, I keep getting redirected to the site URL which should only be used for web, not iOS or Android. Below is the function I am using for Apple but this is happening with all other providers as well.
const isWeb = Platform.OS === "web";
const redirectTo = isWeb
? "https://web.example.com/login-callback/"
: "com.example.react://login-callback/";
export const signInWithApple = async () => {
const { data, error } = await supabase.auth.signInWithOAuth({
provider: "apple",
options: {
redirectTo: redirectTo,
},
});
if (error !== null) {
console.log(error?.message);
return "error";
} else {
console.log(data);
Linking.openURL(data.url);
return "success";
}
};
The URL that gets logged before launching is correct, for example, LOG {"provider": "apple", "url": "https://api.example.com/auth/v1/authorize?provider=apple&redirect_to=com.example.react%3A%2F%2Flogin-callback%2F"}, but I always get redirected to something like https://web.example.com/#access_token=*****. I had a similar issue with Flutter, and that was because I had not added the additional redirect in Supabase but I already did that. I also confirmed that I have CFBundleURLSchemes set in the info.plist for iOS but that did not fix it.
IF SELF-HOSTING:
Check that you do not have spaces after commas in ADDITIONAL_REDIRECT_URLS.
Correct ✅ :
ADDITIONAL_REDIRECT_URLS="URL,URL,URL"
Incorrect ❌ :
ADDITIONAL_REDIRECT_URLS="URL, URL, URL"

Flutter Firebase Sign In With Apple Not Working ios

I am trying to set up with apple sign in with the following code. When tapping the button nothing happens.
I get the following error:
NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("User"))
The new user appears in firebase authentication but other than that the app does not work.
I have enabled sign in with apple in xcode and on developer.apple.com. I have also tried redownloading my provisioning profiles in xcode but no luck.
I have enabled apple sign in in firebase.
Does anyone know how to fix this?
mixin AuthenticationApple {
static String generateNonce([int length = 32]) {
const charset =
'0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._';
final random = Random.secure();
return List.generate(length, (_) => charset[random.nextInt(charset.length)])
.join();
}
/// Returns the sha256 hash of [input] in hex notation.
static String sha256ofString(String input) {
final bytes = utf8.encode(input);
final digest = sha256.convert(bytes);
return digest.toString();
}
static Future<User> signInWithApple({BuildContext context}) async {
User user;
// To prevent replay attacks with the credential returned from Apple, we
// include a nonce in the credential request. When signing in with
// Firebase, the nonce in the id token returned by Apple, is expected to
// match the sha256 hash of `rawNonce`.
final rawNonce = generateNonce();
final nonce = sha256ofString(rawNonce);
// Request credential for the currently signed in Apple account.
final appleCredential = await SignInWithApple.getAppleIDCredential(
scopes: [
AppleIDAuthorizationScopes.email,
AppleIDAuthorizationScopes.fullName,
],
nonce: nonce,
);
// Create an `OAuthCredential` from the credential returned by Apple.
final oauthCredential = OAuthProvider('apple.com').credential(
idToken: appleCredential.identityToken,
rawNonce: rawNonce,
);
try {
// Sign in the user with Firebase. If the nonce we generated earlier does
// not match the nonce in `appleCredential.identityToken`, sign in will fail.
final UserCredential userCredential =
await FirebaseAuth.instance.signInWithCredential(oauthCredential);
user = userCredential.user;
} on FirebaseAuthException catch (e) {
if (e.code == 'account-exists-with-different-credential') {
ScaffoldMessenger.of(context).showSnackBar(
AppWidget.customSnackBar(
content: 'The account already exists with a different credential.',
),
);
} else if (e.code == 'invalid-credential') {
ScaffoldMessenger.of(context).showSnackBar(
AppWidget.customSnackBar(
content: 'Error occurred while accessing credentials. Try again.',
),
);
}
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
AppWidget.customSnackBar(
content: 'Error occurred using Apple Sign-In. Try again.',
),
);
}
return user;
}
}
I just surpassed this issue by using iOS 13.0 for simulator. It seems there's an issue with higher versions when using the simulator but not with physical devices.
You can download and install simulators all the way back to iOS 13.0 (which is the minimum version for Apple Sign-In. In Xcode:
Xcode > Preferences.
Select the "Components" tab.
Mark the simulators you want.
Press "Check and Install Now".

Flutter-Firebase phone Auth always returns Token mismatch on iOS

I'm trying to use phone Authentication and it's working as expected on Android, but on iOS I always get Token mismatch and don't receive a code.
other Firebase services like cloud firestore and email Auth are working fine on iOS.
I made sure of the following:
-APN key is added in Firebase
-Google Services file is updated
-Background Modes and Push Notification capabilities are on
the error message is from PhoneVerificationFailed
Future<void> _verifyPhoneNumber() async {
setState(() {
_message = '';
});
final PhoneVerificationCompleted verificationCompleted =
(AuthCredential phoneAuthCredential) async {
await _auth.signInWithCredential(phoneAuthCredential);
setState(() {
_message = 'Received phone auth credential: $phoneAuthCredential';
});
};
final PhoneVerificationFailed verificationFailed =
(AuthException authException) {
setState(() {
_message = '********************\n\n'
'Phone number verification failed. Code: ${authException.code}.'
'\n Message: ${authException.message}'
'\n\n********************';
});
};
final PhoneCodeSent codeSent =
(String verificationId, [int forceResendingToken]) async {
_verificationId = verificationId;
setState(() {
_message = 'waiting for code';
//waitingCode = true;
});
};
final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
(String verificationId) {
_verificationId = verificationId;
};
try {
await _auth.verifyPhoneNumber(
phoneNumber: number,
timeout: const Duration(seconds: 30),
verificationCompleted: verificationCompleted,
verificationFailed: verificationFailed,
codeSent: codeSent,
codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);
} catch (e) {
print('Error is $e');
}
}
and I'm getting these messages from log
Userinfo {
"com.google.firebase.auth" = {
warning = "This fake notification should be forwarded to Firebase Auth.";
};
}
UserDate : {
"com.google.firebase.auth" = {
warning = "This fake notification should be forwarded to Firebase Auth.";
};
}
UserDate Json : {
"com.google.firebase.auth" : {
"warning" : "This fake notification should be forwarded to Firebase Auth."
}
}
flutter:
TRUE
flutter: Call Back {
"com.google.firebase.auth" : {
"warning" : "This fake notification should be forwarded to Firebase Auth."
}
}
I understand it's too late in answering this. But I also faced the same error recently. I fixed the issue on iOS. Your entire configuration must be valid. There are two settings you need to make.
Remove any method swizzling variable from GoogleService-info.plist
i.e. remove FirebaseAppDelegateProxyEnabled property from plist
In AppDelegate.swift, override this method and set the following
func application(application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
Messaging.messaging().apnsToken = deviceToken
}
It is mentioned at https://firebase.google.com/docs/cloud-messaging/ios/client#token-swizzle-disabled
I am using firebase_messaging: ^6.0.16 and the above settings worked
Changing the Firebase Auth version from 0.14.0 to
firebase_auth:
git:
url: https://github.com/collinjackson/plugins.git
ref: 441417c2fed0ff26bf84a49ab2c5ffd2aa5487de
path: packages/firebase_auth
fixed my issue.
see https://github.com/flutter/flutter/issues/35267 for more details

Google Sign-In JavaScript client not working on PWA App

Since yesterday when I use the gapi.auth2 to do a Google Sign-in on an installed PWA app on Android, the App opens the browser window to select the user, but it remains blank.
The same page on the Chrome browser on Android open the user selection as usual. The code is the same, from the same server. The code was not modified in more than 15 days. I presume the problem is some change in the gapi JS client code from Google servers.
Inspecting the PWA Google Sign-in tab on chrome shows the following error:
Uncaught Failed to get parent origin from URL hash!
The origins on Google Developer Console are ok.
Anyone has any clue how to solve this?
Edit1: Code chunk
initGoogle() {
this.ngRedux.dispatch({ type: SN_INIT_GOOGLE });
Observable.create((observer: Observer<any>) => {
let head = document.getElementsByTagName('head');
(<any>window).__ongload = () => {
gapi.load('auth2', () => {
gapi.auth2.init({
client_id: `${AppConfig.google.clientID}`
}).then(() => {
this.auth2 = gapi.auth2.getAuthInstance();
this.googleInitiated();
observer.complete();
}, (err) => {
this.log.error(err);
observer.error(err);
});
});
};
let script: HTMLScriptElement = document.createElement('script');
script.src = 'https://apis.google.com/js/platform.js?onload=__ongload';
script.type = 'text/javascript';
head[ 0 ].appendChild(script);
}).pipe(
timeout(AppConfig.google.timeout),
retry(AppConfig.google.retries),
catchError(error => {
this.googleInitError();
return observableEmpty();
}),
take(1)
).subscribe();
}
async googleLogin(scope: string = 'profile email', rerequest: boolean = false, type: string = SN_GOOGLE_LOGIN): Promise<GoogleUser> {
let goopts = {
scope: this.ngRedux.getState().socialNetworks.getIn([ 'google', 'grantedScopes' ]),
prompt: rerequest ? 'consent' : undefined
};
try {
const user: GoogleUser = await this.auth2.signIn(<any>goopts);
...
return user;
} catch (error) {
...
return error;
}
}
Edit 2: Error screenshot
Screenshot
I had the similar issue as mentioned here. I had not registered my domain under Credential -> My OAuth Client ID -> Authorized JavaScript origins. By adding, it started working. Check the similar case for your app. It may help.
This bug should be fixed. Cannot reproduce it any more.

Firebase database not working with Facebook Expo authentication

I've been developing an app with React Native (with Expo) and Firebase on the backend. When running the project through Expo client on the iPhone, I can normally login with email and password and then fetch data from Firebase database. But when I login with Facebook, database read hands and it does not resolve anything. Important parts of the code look following:
firebase.initializeApp(firebaseConfig);
// This works everywhere
export const login = async (email, password) => {
await firebase.auth().signInWithEmailAndPassword(email, password);
const userId = firebase.auth().currentUser.uid;
return userId + '';
};
export const loginByFacebook = async () => {
const { type, token } = await Expo.Facebook.logInWithReadPermissionsAsync(FB_APP_ID, {
permissions: ['public_profile'],
});
if (type === 'success') {
const credential = firebase.auth.FacebookAuthProvider.credential(token);
try {
await firebase.auth().signInAndRetrieveDataWithCredential(credential);
} catch (error) {
console.log('cannot login ', error);
}
}
};
export const readData = (key) => {
console.log('getWins ');
const userId = firebase.auth().currentUser.uid;
return firebase
.database()
.ref(`/${key}/${userId}`)
.once('value');
};
...
class PostList extends React.Component {
async componentDidMount() {
// it normally resolves when logged with email & password,
// resolves with facebook auth on iPhone simulator
// does not resolve with facebook auth on Expo client on iPhone
const data = await readData('posts');
}
}
However, what is really strange, that it does not work on iPhone + Expo client, but does on the iPhone simulator. The crucial part is in the async componentDidMount().
Database config is still in the dev mode (allow all read & writes):
{
"rules": {
".read": true,
".write": true
}
}
I've used the following guides: https://docs.expo.io/versions/latest/sdk/facebook
https://docs.expo.io/versions/latest/guides/using-firebase#listening-for-authentication
Are there any more prerequisites that I've forgotten to setup? Or Expo client has limitations in terms of properly handling calls with Facebook auth?

Resources