How can I perform firebase authentication with facebook in flutter [duplicate] - facebook

This question already has answers here:
Function SignInWithFacebook doesn't exist in Firebase Auth SDK for Flutter in macOS, but in Windows it exists
(4 answers)
Closed 3 years ago.
I'm trying to add firebase and facebook authentication in my app. Facebook auth is already done:
final facebookLogin = FacebookLogin();
final result = await facebookLogin.logInWithReadPermissions(['email']);
switch (result.status) {
case FacebookLoginStatus.loggedIn:
final token = result.accessToken.token;
final graphResponse = await http.get(
'https://graph.facebook.com/v2.12/me?fields=name,first_name,last_name,email&access_token=$token');
Map<String, dynamic> user = jsonDecode(graphResponse.body);
// _onGetFacebookUser(user);
I don't know how to perform firebase authentication with facebook result.
I've already watched this answer, but it doesn't help, there is only facebook login code example.
I've found this article, but there is no method signInWithFacebook

You have to use credential
final result = await facebookLogin.logInWithReadPermissions(['email']);
switch (result.status) {
case FacebookLoginStatus.loggedIn:
final token = result.accessToken.token;
AuthCredential fbCredential = FacebookAuthProvider.getCredential(accessToken: token);
FirebaseAuth.instance.signInWithCredential(credential).then((FirebaseUser user) {
// do something...
});
...
UPD:
It worked fine for flutter_facebook_login version 2.0.1
For now for version 3.0.0 there is method 'login':
final result = await facebookLogin.logIn(['email']);

Related

Autofill login credentials in flutter inappWebview

I am using flutter_inappwebview plugin for developing an android browser. Now I need to save and autofill login credentials for different websites like facebook, twitter etc.
I come to know about securely storing login data using flutter_secure_storage plugin but I don't have any knowledge about how to implement this.
I want this feature exactly as it has in Google Chrome. Please help if you can...
Thanks in advance!
flutter_secure_login currently does not support Flutter platform web.
Since this is the case I would recommend using shared_preferences found here
Its very similar to secure storage and can be utilized in a very similar way
in the following code i am using it to store my user data
// write to shared preferences
final prefs = await SharedPreferences.getInstance();
if (!_context.isLoggedIn) {
if (prefs.containsKey('userData')) prefs.remove('userData');
return;
}
final userData = Map<String, String>();
userData['refreshToken'] = _refreshToken;
userData['tenantId'] = _tenantId;
userData['userId'] = _userId;
await prefs.setString('userData', json.encode(userData));
That can then be accessed to refresh tokens.
Future init() async {
final prefs = await SharedPreferences.getInstance();
final prefData = prefs.getString('userData');
if (prefData == null) return;
final Map<String, Object> userData = json.decode(prefData);
_authWriter.write({
'refreshToken': userData['refreshToken'],
'userId': userData['userId'],
'tenantId': userData['tenantId']
});
await refreshAccessToken();
}

How to obtain the refreshToken when google sign in with Flutter / Firebase

I've already did the google sign with the firebase flutter toolkit. When sign in is done, I receive the idToken to read/write on the database.
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();
Future<String> signInWithGoogle() async {
await Firebase.initializeApp();
final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
final UserCredential authResult = await _auth.signInWithCredential(credential);
final User user = authResult.user;
final idToken = await user.getIdToken();
}
The problem is, I need to auto login user when he opens the app again. So, when I sign in with google, I do not receive the refresh token, needed to get the new valid idToken, as the Doc.
How can I get the refreshToken ?
You can use SharedPreferences to set a bool value when a user is logged in from google and check the value when the app restarts. Don't forget to remove this value from shared preferences when user logged out.
I'm pretty sure googl_sign_in keeps the refresh token internally and you always receive a valid idToken. If it's about to expire, you can force renewal.
Answering your direct question about refreshToken:
You can create your own implementation of the google_sign_in class. In the end it's just an OAuth token. Here's a web implementation of a custom google_sign_in service: https://stackoverflow.com/a/69746036/5492496
I'm pretty sure you can do the same for Android & iOS using web view, you will loose the single click functionality on Android though.

Flutter Web Google Sign In

I try to implement a signIn with Google in Flutter Web. I use GoogleSignn 4.1.1 and Firebase Auth 0.15.4. I do not get any error message. It just does not pop up.
I registered the web app in Firebase (Added Dependencies) and even added the <meta> Tag with the google-signin-client_id
The Firebase Auth with Google works when I run it on Android
I also ran the Example App from GoogleSignIn in Web. It also does not pop up.
This is my Login Code (Works on Android)
final FirebaseAuth _auth = FirebaseAuth.instance;
FirebaseUser user = await _auth.currentUser();
if (user != null) {
log.d('alreadyLoggedIn');
} else {
final GoogleSignIn _googleSignIn = GoogleSignIn(clientId: Constants.GOOGLE_SIGN_IN_CLIENT_ID);
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
await _auth.signInWithCredential(credential);
user = await _auth.currentUser();
assert(user.email != null);
assert(user.displayName != null);
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);
}
return user;
}
I hope someone knows how this can be fixed.
Have you followed all of the instructions (including adding OAuth ID to index.html) from this page?
https://pub.dev/packages/google_sign_in_web
You get your CLIENT ID from https://console.developers.google.com/apis/credentials
You also have to run from terminal like this, for it to work on localhost in debug:
flutter run -d chrome --web-hostname localhost --web-port 5000
The default authorised port is 5000, you can add other URIs on the same page you got your CLIENT ID (e.g.8764367243864-987523.apps.googleusercontent.com), it's under "Authorised JavaScript origins"
https://console.developers.google.com/apis/credentials)

Facebook login flutter app error with native login

I am trying to integrate facebook login with Flutter. Facebook login working with FacebookLoginBehavior.webViewOnly but I want to login with native dialog. This is not woking in flutter. (iOS only)....
Future<bool> facebookLogin(
BuildContext context, bool isCoach, AuthMode authMode) async {
final facebookLogin = FacebookLogin();
facebookLogin.loginBehavior = FacebookLoginBehavior.nativeOnly;
final result = await facebookLogin.logInWithReadPermissions(['email']);
print(result.status);
if (result.status == FacebookLoginStatus.loggedIn) {
var _token = result.accessToken.token;
return true;
}
return false;
}
Logs: flutter: FacebookLoginStatus.cancelledByUser
As per the issue list for the plugin this is a bug for iOS 13 (https://github.com/roughike/flutter_facebook_login/issues/195)
Use the device_info package and you can put the following check for the iOS 13 device so the rest of the world enjoys the native view
if (Platform.isIOS){
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
String iosSystemVersion = iosInfo.systemVersion;
if (iosSystemVersion.startsWith('13')){
print('Running on IOS version $iosSystemVersion. Forcing facebook login to be webViewOnly');
_facebookSignIn.loginBehavior = FacebookLoginBehavior.webViewOnly;
}
}

How to connect facebook, firebase and flutter?

I'm following the instructions for incorporating facebook with android projects found here https://developers.facebook.com/apps/318154048893918/fb-login/quickstart/ and there is a step to download the Facebook SDK, but after that, it doesn't tell me where to put the file. The import statement it tells me to add won't work (says target of uri doesn't exist).
I'm trying to add the facebook user to our firebase database when they log in. I'm using flutter in android studio.
There doesn't seem to be anything of use in the console log, except that print statement doesn't print anything. Any ideas?
Here's my code to log in the user.
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
Future<FirebaseUser> initiateFacebookLogin() async {
final FacebookLoginResult result =
await facebookLogin.logInWithReadPermissions(['email', 'public_profile']);
FirebaseUser user =
await _auth.signInWithFacebook(accessToken: result.accessToken.token);
//Token: ${accessToken.token}
ProviderDetails userInfo = new ProviderDetails(
user.providerId, user.uid, user.displayName, user.photoUrl, user.email);
List<ProviderDetails> providerData = new List<ProviderDetails>();
providerData.add(userInfo);
print(user.displayName);
addToDatabase(user.uid, user.displayName, user.displayName, user.email);
return user;
}
In flutter you need use flutter_facebook_login plugin take a look here to see how to get the plugin and setup your flutter app to make use of this plugin. You can also check this article that is step-by-step about how setup you project and contains code example too but the API used is out of date.
Here a snippet with updated API showing how to achieve login in firebase with facebook account.
/// This mehtod makes the real auth
Future<FirebaseUser> firebaseAuthWithFacebook({#required FacebookAccessToken token}) async {
AuthCredential credential= FacebookAuthProvider.getCredential(accessToken: token.token);
FirebaseUser firebaseUser = await _authInstance.signInWithCredential(credential);
return firebaseUser;
}
In your code you're using _auth.signInWithFacebook method that is deprecated and you should replaced by signInWithCredential updating you firebase_auth plugin version.
///This object comes from facebook_login_plugin package
final facebookLogin = new FacebookLogin();
final facebookLoginResult = await facebookLogin
.logInWithReadPermissions(['email', 'public_profile']);
switch (facebookLoginResult.status) {
case FacebookLoginStatus.error:
print("Error");
break;
case FacebookLoginStatus.cancelledByUser:
print("CancelledByUser");
break;
case FacebookLoginStatus.loggedIn:
print("LoggedIn");
/// calling the auth mehtod and getting the logged user
var firebaseUser = await firebaseAuthWithFacebook(
token: facebookLoginResult.accessToken);
}
}