createUserWithEmailAndPassword error operation not allowed (firebase auth enabled) - firebase

I'm new with flutter and firebase. I'm trying to use createUserWithEmailAndPassword function for firebase but when I try to implement the code it's an infinite loop. I used debug mode of android studio and it shows me the errors ERROR_OPERATION_NOT_ALLOWED : The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section. . It seems to be an errors in the firebase authentification but I already enable the authentification with email and password then I don't understand why there is this issue. I copy-paste the json document and I modified the gradle files too as it is mentionned in the google process.
Thanks for the help.

The error says the given sign-in provider is disabled for this Firebase project
You have to enable email and password options in your firebase project.
See screenshots on how to do that below:
1) Go to the authentication tab after clicking your firebase project
2) Select the Sign-In methods tab
3) Enable sign in with email and password
If you are still getting the error, Try running flutter clean in your project.
I hope this helps

FlatButton(onPressed: () async {
if(_formKey.currentState.validate()) {
setState(() => chargement = true);
AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: mdp); //here is the issue
await collectionUser.document(_idUser()).setData({
'idUser' : _idUser(),
'nomComplet' : nomComplet,
'emailUser' : email,
});
if(result == null){
setState(() => chargement = true);
}
}
},
color: Colors.amber,
child: Text("inscription"),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)
),
),

Related

What Sign in method to use best?

We are having a flutter app (ios, android, web), where users are signed in via username & password.
We are also using google firebase since its powerful and easy to integrate.
The username and password mainly belongs to the website where we are gathering data at. (As example - If they use the website without the app, and they change the password, after that he wont be able to login to the app)
Now the mentionned websites host is giving us API access, login via OpenId to get the access token for the API. Because we are a safety risk since we store the passwort of the users too!
For the API access we dont really need to store Username and password of the user, since they are redundant anyway. But if we want to add a feature (for example message sending or further data storage) we need to have the user signed in into firebase.
Upt to now we are using for (first) signin the following snippet:
firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
and for already signed in users :
firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
Notice that similar credentials are also using to login on the API. (Since the user is there already registered)
How can we login on firebase with said information without asking twice for a password ond username (once for us, and once for the API) ?
We already tried :
await firebaseAuth.signInWithCustomToken(token)
with the jwl token from the OpenId, of course it did not work because the token did not contain the uid reference.
SOLUTION
Create a Firebase Cloud Function just like described in Firebase Cloud Functions.
Be aware that if you want to create a customtoken, the cloud functions need rights. On initializeApp(..)
admin.initializeApp({
serviceAccountId: '{App_Name}#appspot.gserviceaccount.com',
});
So the correct service account has to be selected, you also have to give him the rights to generate tokens. (See => Stackoverflow Question
The Cloud Function does then look the following way :
export const functionName= functions.https.onRequest(async (request, response) => {
const id = request.query.id;
const passcode = request.query.passcode; // not really needed
// add other passcodes for different authentications
if (passcode == "{COMPARE SOMETHING}") {
await admin.auth().createCustomToken(id).then((customToken) => {
response.status(200).send({
'id': id,
'customToken': customToken
});
}).catch((error) => {
response.status(500).send({
'ErrorMessage': "No token could be generated",
"Error": error
});
});
}
else {
response.status(500).send({
'ErrorMessage': "Passcode wrong"
});
}
});
On the other hand we have the code on the mobile app :
// Get JWT Token
Map<String, dynamic> jwtpayload =
Jwt.parseJwt(response_decoded['id_token']); // use import 'package:jwt_decode/jwt_decode.dart';
final queryParameters = {
'id': jwtpayload ['sub'],
'passcode': 'APassCode',
};
final uri = Uri.https('us-central1-{yourApp}.cloudfunctions.net',
'/{functionName}', queryParameters);
final cloud_function_api_call = await client.post(uri);
var decoded_cloud_function_api_call =
jsonDecode(cloud_function_api_call.body);
And at the end :
await firebaseAuth.signInWithCustomToken(
decoded_cloud_function_api_call['customToken']);
I hope it helps others facing a similar issue.

FirebaseMessagingError: Invalid registration token provided

I am trying to send push notifications to another iOS device using firebase cloud functions but I receive the following error below when attempting to do so:
'FirebaseMessagingError: Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM.'
This is the registration token I am trying to send to 6e04bb35f06e2d981d5603bbd229eeab5ee5649f6af7b4ecc3894be6ad1574d7 which is the same token I have saved in my realtime database:
Below is my onCreate function:
exports.onMessageCreate = functions.database.ref('/messages/{chatId}/{messageId}').onCreate((snapshot, context) => {
const chatId = context.params.chatId;
const receiverId = chatId.replace(context.auth.uid, '');
const root = snapshot.ref.root;
return admin.database().ref(`/users/${receiverId}/regToken`).once('value').then(tokenSnap => {
var regTokenRef = tokenSnap.val();
const payload = {
notification: {
title: 'title',
body: snapshot.val().text,
}
};
const options = { priority: "high" };
return admin.messaging().sendToDevice(regTokenRef, payload, options).then(function(response){
console.log("Successfully sent message: ", response);
console.log(response.results[0].error);
}).catch(function(error) {
console.log("Error sending message: ", error);
});
});
});
Do you know what may be causing this error? I am not too sure what I need to check here. Is the format wrong here? Does it need to be in quotes? I have looked at other links but they haven't really helped.
I am importing '#react-native-community/push-notification-ios' to generate the token. I think this may be the problem. I was having issues to use the messaging from firebase. Is this the issue?
Please see below the didFinishLaunchingWithOptions method updated in my AppDelegate.m file. Have I placed the below code correctly? When this is added it is causing my app to appear blank when launching the simulator with the FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).? However, when removed my app launches but with still has the FirebaseError.
if ([FIRApp defaultApp] == nil) {
[FIRApp configure];
}
#react-native-community/push-notification-ios is not able to generate an FCM token, only APN token: https://github.com/react-native-push-notification-ios/push-notification-ios/issues/117
If you want to use firebase, you need to generate the token from the messaging package of firebase to have a FCM one.

How to enable firebase phone verification in flutter web ? I have tried many ways but it doesn't seems to work, SMS code need to be sent to the user

I want to implement the phone verification by sending OTP using firebase, how to do this? . I have tried by following this thread in github, but no use it's not helping, signInwithphoneNumber only signs in user not verifies the user by sending SMS OTP code, how to solve this?
Github thread link:https://github.com/flutter/flutter/issues/46021
When I have implemented throwed the following error:
Error: UnimplementedError: verifyPhoneNumber() is not supported on the web. Please use
`signInWithPhoneNumber` instead.
Can someone help me out please !!!
You have to use
FirebaseAuth auth = FirebaseAuth.instance;
// Wait for the user to complete the reCAPTCHA & for an SMS code to be sent.
ConfirmationResult confirmationResult = await auth.signInWithPhoneNumber('+44 7123 123 456');
then this to verify
UserCredential userCredential = await confirmationResult.confirm('123456');
You can also add RecaptchaVerifier as per your own use like
ConfirmationResult confirmationResult = await auth.signInWithPhoneNumber('+44 7123 123 456', RecaptchaVerifier(
container: 'recaptcha',
size: RecaptchaVerifierSize.compact,
theme: RecaptchaVerifierTheme.dark,
));
and you can also edit reCaptcha
RecaptchaVerifier(
onSuccess: () => print('reCAPTCHA Completed!'),
onError: (FirebaseAuthException error) => print(error),
onExpired: () => print('reCAPTCHA Expired!'),
);

How to use Windows Authentication (Azure AD) in Flutter with Firebase

I am currently developing an app which requires windows authentication.
Access should only been given to users known in the azure active directory of the company.
I already:
created an app registration with read access to azure.
activated windows auth in my firebase project
There is some example code available on:
https://firebase.google.com/docs/auth/android/microsoft-oauth?authuser=0
but it is not very well explained where I can get some of the used classes like 'OnSuccessListener' etc.
I would appreciate if someone can provide me some best practice code how to use the windows auth in flutter with firebase or also without firebase. Hopefully there is a possibility without storing the app registration secretly in the code.
In the end I need the usertoken to make api calls.
Without Firebase you have the msal_mobile [1] package that will Authenticate with Azure AD on iOS and Android.
There's step-by-step instructions within the package for setting up within the Azure portal, along with the iOS and Android platforms. Then the Flutter code to sign-in is simply:
await msal.signIn(null, ["api://[app-registration-client-id]/user_impersonation"]).then((result) {
print('access token: ${result.accessToken}');
})
Link
[1]: https://pub.dev/packages/msal_mobile
There is now a way for you to sign in with Microsoft using Firebase Auth but at the time of writing, I haven't seen a way to use it in tandem with MS Graph. For those who don't need graph access, here's the method I used:
Pubspec.yaml
firebase_auth: ^0.18.3
firebase_core: ^0.5.2
Your Widget
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: RaisedButton(
child: Text('login'),
onPressed: () async {
try {
User user =
await FirebaseAuthOAuth().openSignInFlow("microsoft.com", [
"https://graph.microsoft.com/User.Read",
"https://graph.microsoft.com/User.ReadBasic.All"
], {
'tenant': '' //Your tenant ID here
});
print(user);
} on PlatformException catch (error) {
debugPrint("${error.code}: ${error.message}");
}
},
),
),
);
}
}
Assuming you've setup Firebase Auth and Azure App registrations properly, this should be enough for you to sign in via MS

Firebase signInWithCredentials from Microsoft Azure

Normally, I'd use the firebase.auth.OAuthProvider('microsoft.com') and pass it to firebase.auth().signInWithPopup() but in my case I need to log into Microsoft first using their library and pass the credentials back to firebase. (why? because I need their accessToken/refreshToken handling which isn't done by firebase).
Anyway, I can't seem to find a way to take the microsoft-supplied credentials and pass them successfully back to firebase...
here's what's not working for me:
export async function msLogin() {
const userAgent = new MSAL.UserAgentApplication({ auth: { clientId: CLIENT_ID, } });
const auth = await userAgent.loginPopup({ scopes: ['profile'] });
const provider = new firebase.auth.OAuthProvider('microsoft.com');
const idToken = auth.idToken.rawIdToken;
const credential = provider.credential(idToken);
await firebase.auth().signInWithCredential(credential); // **** THIS FAILS
// ... with "Invalid IdP response/credential: http://localhost?id_token=eyJ0eXAiO...0e9BeTObQ&providerId=microsoft.com"
The microsoft popup part works great and I'm logged in successfully there and able to issue API calls. But I can't get firebase to accept those credentials to log in on firebase. I've enabled the Microsoft OAuth provider in the Firebase Authentication panel and I'm sure the CLIENT_ID's match...
Maybe I'm constructing the OAuthCredential wrong?
Help greatly appreciated!
ps: this is a continuation of this SO post.

Resources