What are access token and refresh token from firebase auth result - firebase

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);
});

Related

How to return data to client using beforeSignIn Firebase Function

I need 5 properties from Firebase Authentication in order to Authenticate with the Google Classroom API.
I can get the user's accessToken after signing in with popup as follows:
const provider = new GoogleAuthProvider();
const SCOPES = [
'https://www.googleapis.com/auth/classroom.courses.readonly',
'openid', ...etc
];
for (let scope of SCOPES) {
provider.addScope(scope);
}
provider.setCustomParameters({
access_type: 'offline',
prompt: 'consent',
});
signInWithPopup(auth, provider)
.then(async (result) => {
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
}
)
But I also need the refreshToken, clientId, clientSecret and expiryTime.
I know that I can access a few of these by using the beforeSignIn cloud function with the appropriate settings checked off in the firebase console.
exports.beforeSignIn = functions.auth.user()
.beforeSignIn((user, context) => {
const refreshToken = context.credential.refreshToken;
const expiryTime = context.credential.expirationTime;
// How do I return these to the client?
});
I also note that credential.secret is always empty and that clientId is not present anywhere in the user or context arguments of the cloud function.
If it is not possible to return these from the Function, is there any other way I can get these 5 properties from Firebase Authentication on the web, so that I can authenticate the Google Classroom API in an external service?
I am using Firebase Admin version: 11.0
Using Google Identity Platform for Firebase Auth

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.

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.

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.

Firebase customToken workflow (ICW Angular2 & Express)

I'm trying to wrap my head around the best way to handle the creation of a customToken with Firebase in a secure way.
This is what I came up with:
The user logs in on the client side with email and password. firebase.auth().signInWithEmailAndPassword(email, password)
Storing the current UID of the user in local storage. localStorage.setItem('uid', response.uid);
Get the JWT token of the current user. firebase.auth().currentUser.getToken(true) and store the token in localStorage localStorage.setItem('token', res)
Make a post call to the server and add the token to Authorization header and send the UID in the body. const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', localStorage.getItem('token'));
this.http.post('/api/login', localStorage.getItem('uid'), {
headers: headers
})
On the serverside verify the token const authorization = req.headers.authorization; admin.auth().verifyIdToken(authorization). If valid set the UID this.uid = decodedToken.uid;
Now generate the custom token. Add the additionalClaims const additionalClaims = {
premiumAccount: true }; and call the createCustomToken function. admin.auth().createCustomToken(this.uid, additionalClaims)
Send the custom token back to the client res.status(200).send({
token: customToken
})
On the client side login with the customToken. firebase.auth().signInWithCustomToken(data.token)
Is this summary a good practice or are there better ways to handle this?

Resources