How to get refresh token for google api using Firebase authentication - firebase

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.

Related

How i get new access token when current access token has expired, google firebase auth?

I use firebase at client and use firebase-admin at server.
At client i use signInWithPopUp to sign in to my web app with google account, then receive accessToken, expirationTime, refreshToken at client.
stsTokenManager:{
accessToken: "eyJhbGciOiJzGcaUzI1JKKIsIzxcXzStpZC... ,
expirationTime: 1648809531166 ,
refreshToken: "AIwxAjDfh8_SkckvoSsASxXllMkIX8GBNx...
And i use verify function in firebase-admin lib for verify token was send by client, but until token has expired(1h), i can't use this token.
How i get new accesstoken when current access token has expired?
You don't have to necessarily have to read user's idToken, store it anywhere or refresh it yourself. Instead you just need to use getIdToken() to get user's ID Token. If the token has expired, Firebase SDK will refresh and return a new token or return existing one. You can use getIdToken() before every request to your API.
const userToken = await firebase.auth().currentUser.getIdToken();
// pass userToken to in the API request
// API request here
You can use the following to obtain the oauth access token:
const provider = new GoogleAuthProvider()
provider.addScope(...)
...
const result = await signInWithPopup(auth, provider)
const credential = GoogleAuthProvider.credentialFromResult(result)
console.log(credential.accessToken)
I don't know how to refresh that token.

Create firebase auth from google auth token

I am using firebase google auth to manage users. Further, I have to integrate the users calendar using the calendar API, now firebase auth provides ID Token, ID Refresh token & oAuth token but not oAuth refresh token, due to which I will have to obtain the oAuth token & oAuth refresh token using gAPI, now I got that, but is there a way to use those tokens to create a firebase auth user? I know there is method to create sign in with signInWithCredential but this takes ID Token and not oAauth token.
UPDATE
Sign In code:
const { client_secret, client_id, redirect_uris } = credentials.web;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
// Get code from the URL
oAuth2Client.getToken(code, (err, token) => {
oAuth2Client.setCredentials(token);
});
After gAPI signin, I am getting following details:
{
"access_token": "xxx",
"refresh_token": "xxx",
"scope": "https://www.googleapis.com/auth/calendar",
"token_type": "Bearer",
"expiry_date": 1613023105889
}
To access the ID Token, you have to add additional scope to the GAPI OAuth request. Along with your calendar scope, add "openid". Then in the token response, you should have access to id_token.
Also, you can skip the above step and exchange the OAuth token from google with firebase to get firebase ID Token.
Official docs: https://firebase.google.com/docs/reference/rest/auth/#section-sign-in-with-oauth-credential

Retrieving Firebase Twitter Auth tokens after initial sign in

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.

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