Retrieving Firebase Twitter Auth tokens after initial sign in - firebase

Just following the firebase twitter auth guide and I'm curious if there is a way to retrieve the twitter accessToken and secret after the first sign in.
You can retrieve these after logging in the first time with
firebase.auth().getRedirectResult().then(function (result) {
if (result.credential) {
// This gives you a the Twitter OAuth 1.0 Access Token and Secret.
// You can use these server side with your app's credentials to access the Twitter API.
var token = result.credential.accessToken;
var secret = result.credential.secret;
console.log([token, secret]);
// ...
}
// The signed-in user info.
var user = result.user;
//console.log(user);
}).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
However, based on my understanding, this is only run the first time after logging in with Twitter.
How can I retrieve their twitter accessToken and secret when they open the page again? Should I store them when I get them the first time?

You can't. Firebase Auth does not store these credentials. If you need them for later use, you would need to programmatically store them after first sign-in. You could use Firebase realtime database/Firestore to do so but make sure that they can only be accessed by the corresponding authenticated user or not publicly accessible if you plan to use them server side.

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.

What are access token and refresh token from firebase auth result

I set up my APP and can get an auth result by using firebase.auth.OAuthProvider('google.com'). Inside the returned result, there is an User object that contains refreshToken. Is this the refresh token generated by google.com so I can use it later to refresh an access token which will be used to access gmail? I am talking about this field [google reference].(https://firebase.google.com/docs/reference/js/firebase.User#refreshtoken)
My second question is where is the access token from google.com? Is it the credential.idToken?
const auth = firebase.auth();
var provider = new firebase.auth.GoogleAuthProvider();
const provider = new firebase.auth.OAuthProvider("google.com");
const currentUser = auth.currentUser;
auth.signInWithPopup(provider).then((result) => {
console.log(result.user) // contains `refreshToken`
console.log(result.credential.idToken) // is `idToken` access token?
}).catch((reason) => {
reject(reason);
});

How to get refresh token for google api using Firebase authentication

From firebase's documentation
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the
Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
Is there anyway I can get the refresh token for google api using firebase authentication. I couldn't find anything about this problem in Firebase's documentation. I am also aware that the User object also contains a refreshToken. Can I use that refreshToken from firebase to generate a new access_token for google api ?
Firebase Auth is currently focused on AuthN and not AuthZ. They do not manage OAuth tokens on sign in. All OAuth refresh tokens are discarded and only the initial OAuth access token is returned. If you need a Google refresh token, or a Google access token continuously, consider using GApi library to get a Google ID token/access token and then sign in with that to Firebase.
function onGoogleSignIn(googleUser) {
var googleIdToken = googleUser.getAuthResponse().id_token;
firebase.auth().signInWithCredential(
firebase.auth.GoogleAuthProvider.credential(googleIdToken));
}
You will always have the ability to get a Google OAuth access token from the Google sign in library that way.

Google Sign-In using Firebase in React Native

Note the question might be long because of the need for explanation otherwise it might be very vague and lead to same old answers.
I am having problem in creating a Google Sign-In page in React Native using firebase. Based on firebase documentation:
With the updates in the 3.1.0 SDK, almost all of the JavaScript SDK’s
functionality should now work smoothly in React Native. But there are
a couple caveats:
"Headful" auth methods such as signInWithPopup(), signInWithRedirect(), linkWithPopup(), and linkWithRedirect() do not
work in React Native (or Cordova, for that matter). You can still sign
in or link with a federated provider by using signInWithCredential()
with an OAuth token from your provider of choice.
which means I cannot use following code in my React Native project:
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
Then with some googling and searching over dozens of stackoverflow, I found following way to use use Google SignIn using Firebase API
in React Native project as:
const provider = firebase.auth.GoogleAuthProvider;
const credential = provider.credential(token);
firebase.auth().signInWithCredential(credential)
.then((data) => {
console.log('SUCCESS', data);
})
.catch((error) => {
console.log('ERROR', error)
});
Now in just above code, you might have noticed token in following line:
const credential = provider.credential(token);
So based on firebase documentation, token is obtained as follows:
// `googleUser` from the onsuccess Google Sign In callback.
var token = googleUser.getAuthResponse().id_token;
So my question is how do I obtain that token using GoogleUser object or whatever it is in React Native? Or is there another way?
I am going to assume you've added GoogleSignin to your project. If not, you can find a pretty good instruction here
The callback that Google provides has an item, called idToken, which can be used to login via google into your firebase. Once you have returned that object from Google Signin, EG
GoogleSignin.signIn()
.then((user) => { this.loginWithGoogle(user) });
You can simply use this user object's idToken as a credential,
loginWithGoogle = (user) => {
var credential = firebase.auth.GoogleAuthProvider.credential(user.idToken);
and then log into firebase using that credential
firebase.auth().signInWithCredential(credential).then(u => {
//blah blah bleep
}
Hope this helps.

Access scope data after Firebase authentication

I authorized the calendar api in my google sign in auth, using the following code (Angularfire2):
let auth = new firebase.auth.GoogleAuthProvider();
auth.addScope('https://www.googleapis.com/auth/calendar');
this.afAuth.auth
.signInWithPopup(auth).then((data) => {
console.log(data); // nothing about calendar here
});
Is there any way to access authorized scopes using FirebaseAuth?
For example, access the calendar data after the user signs and authorizes the calendar auth.
If you check out the reference docs, you'll see that there are examples for each provider, which demonstrate how to obtain the third-party OAuth token:
// Using a redirect.
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Google Access Token.
var token = result.credential.accessToken;
}
var user = result.user;
});
Once you have the third-party token, you can use that directly against their APIs.

Resources