Flutter ,Google apis wants choose gmail adress every time - flutter

I'm using google calender API and google sign-in in Flutter but when I try to log in, google wants to choose Gmail address every time.
When I was using google sign in without google calender API, my app was logging in automatically after the first login. Then I added google calender API and Google starts to wants me to choose a Gmail account every time.
How can I choose Google signed-in account for google API?
There is the code.
final GoogleSignIn googleSignIn = GoogleSignIn(
clientId:"THIS IS CLIENT ID"
scopes: [
'https://www.googleapis.com/auth/calendar',
],
);
clientViaUserConsent(ClientId(googleSignIn.clientId, ''),
[CalendarApi.CalendarScope], prompt)
.then((AuthClient client) {
Constants.baseCl = client;
});
void prompt(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

Related

Flutter app does not return to the app post user authentication from Google Oauth

I have created a flutter app which adds calendar events to user's google calendar using the google Calendar API. The app is doing the job but I have the following problem.
The app has initializeCalendarApi(); function(code attached below) in the initState() function which authenticates the user using Google Oauth. This is done by redirecting the user to user's browser where they select their Google account and click Allow to allow app to access their calendar. The problem is, once the authentication is done, the browser window is not closed automatically and the user has to close the browser app and shift to the flutter app manually which is bad for a production app.
How do I resolve this to make sure the user automatically gets back to the flutter app after clicking Allow.
Future<void> initializeCalendarApi() async {
var _clientID = new ClientId(Secret.getId(), "");
const _scopes = const [calendar.CalendarApi.calendarScope];
await clientViaUserConsent(_clientID, _scopes, prompt)
.then((AuthClient client) async {
CalendarClient.calendar = calendar.CalendarApi(client);
});
}
Image shows the final Page Obtained in browser after Oauth has been completed. I want to return my flutter app after successful authentication rather than this window opened in browser.

How to sign a Azure AD user into Firebase in a Flutter mobile app?

For a Flutter mobile app I am trying to use a Microsoft OAuthProvider to get a Firebase credential with which to sign the user into Firebase with their Azure AD account.
The closest I got was using a third party Active Directory auth package to log the user in and get an access token. However the sign-in to Firebase fails with an error message that suggests the idToken is invalid.
final AadOAuth oauth = new AadOAuth(config);
await oauth.login();
// accessToken looks legit
String accessToken = await oauth.getAccessToken();
String idToken = await oauth.getIdToken();
OAuthProvider provider = OAuthProvider('microsoft.com');
// Also tried the constructor without the idToken
OAuthCredential credential = provider.credential(accessToken: accessToken, idToken: idToken);
// app fails here:
await FirebaseAuth.instance.signInWithCredential(credential);
// this works fine, but only on web platform:
await FirebaseAuth.instance.signInWithPopup(provider);
Because it is a platform specific error (iOS in this case), the exception details are not surfaced. All I get is:
PlatformException(internal-error, ) nativeErrorCode: 17999
Here is my app settings in the Azure portal:
Full manifest here
Has anyone been successful in using Microsoft Auth to sign a user in to Firebase in a Flutter mobile app?
You can use Firebase Auth OAuth package for it.
And sign in to the firebase using the Microsoft Auth provider.
User user = await FirebaseAuthOAuth().openSignInFlow(
"microsoft.com", ["email openid"], {'tenant': 'your-tenent-id'});
This integrates nicely with firebase so, firebase authStateChange also works with this method.
You have just to not receiving idToken, just verify that you have add the id_token for the response_type and also openid scope like
provider.addScope('openid');
Also check weather you have allowed implicit flow with id token in the Azure portal app settings (you sould check ID tokens on the Authentication tab under Implicit grant section).
Ok than have you added Microsoft as a authentication provider in the firebase authentication configuration Sign-in method page? And also have you tried to authenticate with Auth, after getCredentials method as stated in the documentation?
provider.getCredentialWith(nil) { credential, error in
if error != nil {
// Handle error.
}
if credential != nil {
Auth().signIn(with: credential) { authResult, error in
if error != nil {
// Handle error.
}
// User is signed in.
// IdP data available in authResult.additionalUserInfo.profile.
// OAuth access token can also be retrieved:
// authResult.credential.accessToken
// OAuth ID token can also be retrieved:
// authResult.credential.idToken
}
}
}
firebase authentication package has a method called signInWithPopup so you don't need firebase_auth_oauth anymore. here my code:
Future<UserCredential?> loginWithMicrosoft() async {
OAuthProvider provider = OAuthProvider('microsoft.com');
provider.setCustomParameters({
"tenant": "your-tenant-id",
});
provider.addScope('user.read');
provider.addScope('profile');
try {
final userCredential = await FirebaseAuth.instance.signInWithPopup(provider);
return userCredential;
} on FirebaseAuthException catch(err) {
debugPrint(err.message);
// Handle FirebaseAuthExceptions
// ex: firebase_auth/account-exists-with-different-credential
}
}
Remeber add the redirect URI and enable de scopes in Azure Portal.

How to show Oauth Consent screen in flutter

I am trying to user gmail api. Google is asking me to make a video with demo of Oauth consent screen.
While searching in the internet I have found solutions for web and native android android. The docs of flutter packages googleapi and googleapi_auth were not very helful. If anyone has already implemented any suggestions would be helpful.
It's probably too late but here is the code for
' clientViaUserConsent(_clientid, _scopes, userPrompt)
.then((AuthClient client) {
//your code to authenticate any of your google platform
}
Here is the userPrompt function
void userPrompt(String url) async {
if (await canLaunch(url)) {
print("Launching url");
launch(url);
} else {
print("unable to launch the url");
}}
So whenever the clientviauserprompt is called the prompt function will launch the url to the default browser for the user consent.
You have to use urllauncher dependency for this.

Flutter - How to link social account using Firebase facebook and google plugin

I have a flutter app and would like the user to authenticate both with FB and Google. I do not want multiple accounts, just a single account that links both.
I am using :
firebase_auth 0.15.1
google_sign_in 4.0.14
facebook_plugin 3.0.0
I am not able to get the email address of the user when the user's account already exist with a different provider. The email is needed in order to get the list of providers for that user using the API call "fetchSignInMethodsForEmail"
Here is an example:
1: User login with Google credentials. The account is created in firebase and google is linked.
2: The user now logoff
3: The user now tries to login with FB with the same email.
-- User get the following error
code:"ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL"
details: null
message: "An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address., **null**))
As you can see the email is null. I need the email in order to get a list of providers. Then I can redirect the user to correct provider
here is a snippet of my code
Future<FirebaseUser> signInWithFacebook({bool isIos}) async {
AuthCredential credential;
try {
final FacebookLoginResult result = await facebookLogin.logIn(['email']);
if (result.accessToken != null) {
credential = FacebookAuthProvider.getCredential(
accessToken: result.accessToken.token
);
AuthResult authResult = await _firebaseAuth.signInWithCredential(
credential,
);
firebaseUser = authResult.user;
return firebaseUser;
} catch (e) {
throw Exception(e);
}
return null;
}
Thanks for your help

Actions on Google new SignIn() is cancelling before user can give input

We are creating an Action on Google using Dialogflow V2 API. We are using firebase cloud functions for our fulfillment and we are using an external rest api for our crud operations.
We have an undeployed action that I have tested in the simulator. The conversation flow is
The user is prompted to signin ie, new SignIn()
They are asked what they want to do and they respond
Their response is saved in our backend using their credentials
new SignIn() works in the simulator, but when I test on the Google Home Mini the SignIn() responds as if the user has rejected the propmpt to signin before they have time to respond
Is there some restriction regarding testing an Action that include Account Linking on the Google Home Mini?
The intent containing the new SignIn() is my Welcome intent, could that be causing the issue?
Here are the two intents handling SignIn(). Start Signin Intent is triggered by the Welcome Event
app.intent("Start Signin", (conv) => {
conv.ask(new SignIn());
});
app.intent("Get Signin", (conv, params, signin) => {
if (signin.status === "OK") {
const payload = conv.user.profile.payload;
conv.ask(`I got your account details, ${payload.name}. What do you want to do?`);
} else {
conv.ask(`I won't be able to save your data, please login`);
}
});