how to get token from firebase auth - flutter

I need to get token from firebase when i do auth and then transfer token to backend.I have several cases auth.I have not worked with token yet.What should i do for next step?
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
Future<FirebaseUser> getCurrentUser() => _firebaseAuth.currentUser();
Future<AuthResult> signInWithGoogle() async {
final authentication = await GoogleAuth().signIn();
final credential = GoogleAuthProvider.getCredential(
accessToken: authentication.accessToken,
idToken: authentication.idToken,
);
return _firebaseAuth.signInWithCredential(credential);
}
Future<AuthResult> signInWithEmail(String email, String password) {
return _firebaseAuth.signInWithEmailAndPassword(
email: email,
password: password,
);
}

Are you looking for something like this?
final UserCredential authResult = await _firebaseAuth.signInWithCredential(credential);
final token = authResult.credential.token;

Related

Is it possible to fetch emails from pop3 using sign in with google rather than app password?

I am fetching emails from pop3 with app password which is working perfectly fine. Can I replace app password with sign-in with google? I am using enough_email package.
I am done like this:
await popClient.connectToServer(host, port, isSecure: true);
await popClient.login(email!, token!);
and signing with google like this:
FirebaseAuth auth = FirebaseAuth.instance;
User? user;
final GoogleSignIn googleSignIn = GoogleSignIn();
final GoogleSignInAccount? account = await googleSignIn.signIn();
final GoogleSignInAuthentication authentication = await account.authentication;
final AuthCredential authCredential = GoogleAuthProvider.credential(
accessToken: authentication.accessToken,
idToken: authentication.idToken,
);
final UserCredential userCredential = await auth.signInWithCredential(authCredential);
user = userCredential.user;
I already tried to login with accessToken and idToken but getting PopException -ERR [AUTH] Username and password not accepted
After some research I found the following documents
https://developers.google.com/gmail/imap/xoauth2-protocol
https://developers.google.com/identity/protocols/oauth2
that leads me to the right direction. To authenticate client using sign-in with google. Here is my code for reference:
ImapClient imapClient = ImapClient();
await imapClient.connectToServer("imap.google.com", 993, isSecure: true);
await imapClient.authenticateWithOAuth2(user, accessToken);
await imapClient.selectInbox();
final FetchImapResult result = await imapClient.fetchRecentMessages();
List<MimeMessage> mimeMessages = result.messages;
for (MimeMessage mimeMessage in mimeMessages) {
print(mimeMessage.decodeTextPlainPart());
}
await imapClient.disconnect();
user: email address
accessToken: google sign-in authentication token

How can i get the access token through google sign in -- Flutter

I want to get the access token from google sign and save it as a variable so I'll be able to push it to my own API , this question has been asked before but the answers are outdated . I'm using this package :Google sign in
her,s my log in code that i access through a button :
GestureDetector(
onTap: () {
_googleSignIn.signIn().catchError((e) {
print('Erorr');
});
;
},
To get access token when logged in with google use
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth?.accessToken,
idToken: googleAuth?.idToken,
);
Full method:
import 'package:google_sign_in/google_sign_in.dart';
Future<UserCredential> signInWithGoogle() async {
// Trigger the authentication flow
final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
// Obtain the auth details from the request
final GoogleSignInAuthentication? googleAuth = await googleUser?.authentication;
// Create a new credential
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth?.accessToken,
idToken: googleAuth?.idToken,
);
// Once signed in, return the UserCredential
return await FirebaseAuth.instance.signInWithCredential(credential);
}
for document https://firebase.flutter.dev/docs/auth/social/
Future<bool> google() async {
try {
final googleUser = await googleSignIn.signIn();
final googleAuth = await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth?.accessToken,// accessToken
idToken: googleAuth?.idToken,
);
users = (await auth.signInWithCredential(credential)).user;
if (users == null) {
return false;
}
return true;
} catch (e) {
print('this is error .......$e');
return null;
}
you can get the access token
googleAuth.accessToken //fellowing my code
Future<FirebaseUser> signInWithGoogle(SignInViewModel model) async {
model.state =ViewState.Busy;
GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
AuthResult authResult = await _auth.signInWithCredential(credential);
_user = authResult.user;
assert(!_user.isAnonymous);
assert(await _user.getIdToken() != null);
FirebaseUser currentUser = await _auth.currentUser();
assert(_user.uid == currentUser.uid);
model.state =ViewState.Idle;
print("User Name: ${_user.displayName}");
print("User Email ${_user.email}");
}

Flutter : Errors appearing after updating the Firebase auth package

I created the Firebase Auth class a year ago. Now After updating the Dart language and updating the firebase auth package some errors appeared.
import 'package:firebase_auth/firebase_auth.dart';
class AuthService {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
Stream<String> get onAuthStateChanged => _firebaseAuth.onAuthStateChanged.map(
(FirebaseUser user) => user.uid,
);
// Sign up Email & passowrd
Future<String> createUserWithEmailAndPassword(
String email, String password, String name) async {
final currentUser = await _firebaseAuth.createUserWithEmailAndPassword(
email: email,
password: password,
);
//updat username
var userUpdateInfo = UserUpdateInfo();
userUpdateInfo.displayName = name;
await currentUser.updateProfile(userUpdateInfo);
await currentUser.reload();
return currentUser.uid;
}
// sign in Email & password
Future<String> sinInWithEmailAndPassword(
String email, String password) async {
return (await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password))
.uid;
}
// sign out
signOut() {
return _firebaseAuth.signOut();
}
}
click here to see error
All firebase plugins for flutter since a year ago have a lot of breaking changes you should go to firebase.flutter.dev and check it
I've been trying and searching for more than two weeks The error appears in the code:
//updat username
var userUpdateInfo = UserUpdateInfo();
userUpdateInfo.displayName = name;
await currentUser.updateProfile(userUpdateInfo);
await currentUser.reload();
return currentUser.uid;
}
The method 'UserUpdateInfo' isn't defined for the type 'AuthService'

i'm not able to get FirebaseUser Method...! alredy add packege Firebse Auth [duplicate]

I'm new to Flutter. I have an Issue with Firebase Auth/ Google Auth
The FirebaseUser is not defined
Code:
FirebaseAuth _auth = FirebaseAuth.instance;
GoogleSignIn googleSignIn = GoogleSignIn();
Future<FirebaseUser> currentUser() async { // The Issue is here in the Future<>
final GoogleSignInAccount account = await googleSignIn.signIn();
final GoogleSignInAuthentication authentication =
await account.authentication;
final GoogleAuthCredential credential = GoogleAuthProvider.getCredential(
idToken: authentication.idToken, accessToken: authentication.accessToken);
final AuthResult authResult = await _auth.signInWithCredential(credential);
final FirebaseUser user = authResult.user; // and here as I can't define this FirebaseUser object to return
return user;
}
Pubspec.yml
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.3
firebase_auth: ^0.18.0
location: ^3.0.2
page_transition: ^1.1.6
google_sign_in: ^4.5.1
flutter_facebook_login: ^3.0.0
firebase_database: ^4.0.0
I also face the same issue with AuthResult
final AuthResult authResult = await _auth.signInWithCredential(credential);
Starting from Version firebase_auth 0.18.0:
In the newest version of firebase_auth, the class FirebaseUser was changed to User, and the class AuthResult was changed to UserCredential. Therefore change your code to the following:
Future<User> currentUser() async {
final GoogleSignInAccount account = await googleSignIn.signIn();
final GoogleSignInAuthentication authentication =
await account.authentication;
final GoogleAuthCredential credential = GoogleAuthProvider.credential(
idToken: authentication.idToken,
accessToken: authentication.accessToken);
final UserCredential authResult =
await _auth.signInWithCredential(credential);
final User user = authResult.user;
return user;
}
FirebaseUser changed to User
AuthResult changed to UserCredential
GoogleAuthProvider.getCredential() changed to GoogleAuthProvider.credential()
onAuthStateChanged which notifies about changes to the user's sign-in state was replaced with authStateChanges()
currentUser() which is a method to retrieve the currently logged in user, was replaced with the property currentUser and it no longer returns a Future<FirebaseUser>.
Example of the above two methods:
FirebaseAuth.instance.authStateChanges().listen((event) {
print(event.email);
});
And:
var user = FirebaseAuth.instance.currentUser;
print(user.uid);
Deprecation of UserUpdateInfo class for firebaseUser.updateProfile method.
Example:
Future updateName(String name, FirebaseUser user) async {
var userUpdateInfo = new UserUpdateInfo();
userUpdateInfo.displayName = name;
await user.updateProfile(userUpdateInfo);
await user.reload();
}
now
import 'package:firebase_auth/firebase_auth.dart' as firebaseAuth;
Future updateName(String name, auth.User firebaseUser) async {
firebaseUser.updateProfile(displayName: name);
await firebaseUser.reload();
}
Since firebase_auth 0.18.0, the class FirebaseUser was changed to User
In the newest version of firebase_auth, the class FirebaseUser was changed to User, and the class AuthResult was changed to UserCredentail. Therefore change FirebaseUser to User
The class FirebaseUser was changed to User
try this way
_registerUser() async {
try {
final User? user =
(await FirebaseAuth.instance.signInWithEmailAndPassword(
email: emailCtrl.text,
password: passCtrl.text,
))
.user;
FirebaseFirestore.instance.collection('users').doc().set({
'name': nameCtrl.text,
'uid': user!.uid,
'email': user.email,
'isEmailVerified': user.emailVerified, // will also be false
'photoUrl': user.photoURL, // will always be null
});
print("Created");
} catch (e) {
print(e.toString());
}
}
Run
flutter pub get
Then rebuild your app.
This can be your signin function with email and password as of Sept 2020.Initialze app is a new introduced method we must at least call once before we use any other firebase methods.
Future<void> signin() async {
final formState = _formkey.currentState;
await Firebase.initializeApp();
if (formState.validate()) {
setState(() {
loading = true;
});
formState.save();
try {
print(email);
final User user = (await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password))
.user;
} catch (e) {
print(e.message);
setState(() {
loading = false;
});
}
}
}

Youtube Login Api OAuth 2.0 flutter

I've been trying for a bit to implement login of youtube channels on my app. but all I could do was google accounts with google_sign_in 4.5.1
has any of you implemented this feature and can give me an hint? youtube docs are terrible
edit:
here's the code
class AuthService {
String oAuthClientId = '**hidden**'; // not used?
static List<String> scopes = [
'email',
'https://www.googleapis.com/auth/youtube', // Youtube scope
];
final FirebaseAuth auth = FirebaseAuth.instance;
GoogleSignIn googleSignIn = GoogleSignIn(
scopes: scopes,
);
Future<FirebaseUser> login() async {
final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
final token = googleSignInAuthentication.accessToken;
final AuthResult authResult = await auth.signInWithCredential(credential);
final FirebaseUser user = authResult.user;
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);
final FirebaseUser currentUser = await auth.currentUser();
assert(user.uid == currentUser.uid);
var client = new http.Client();
return currentUser;
}
void signOut() {
auth.signOut();
googleSignIn.disconnect();
}
Future<FirebaseUser> getUser() async{
final FirebaseUser user = await auth.currentUser();
return user;
}
}
To display your youtube channels, you'll need to add the youtube scope https://www.googleapis.com/auth/youtube to your google login.
Prior to this, you must've setup enabled the Youtube api from your developer console. Read the Youtube API documentation for more information
Example login code:
login() async {
GoogleSignIn googleSignIn = GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/youtube', // Youtube scope
],
);
final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
// You'll need this token to call the Youtube API. It expires every 30 minutes.
final token = googleSignInAuthentication.accessToken;
final AuthResult authResult = await auth.signInWithCredential(credential);
final FirebaseUser user = authResult.user;
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);
final FirebaseUser currentUser = await auth.currentUser();
assert(user.uid == currentUser.uid);
}