Get refresh token with Google Auth Provider on Firebase - javascript

I am using Firebase's GoogleAuthProvider in my Vue 2 app to login user. I added the calendar to the provider's scope the get access to the user's calendar. I then use the access_token given in the result to retrieve the events. The problem is the accessToken expires after one hour. How can I renew it?
Here is my code to handle the login:
const auth = getAuth();
const provider = new GoogleAuthProvider();
provider.addScope("https://www.googleapis.com/auth/calendar");
const result = await signInWithPopup(auth, provider);
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
const user = result.user;
await this.checkUser(user, token);

Related

The request action is invalid for firebase authentication with Google

import { auth } from "../../../firebase";
import { GoogleAuthProvider, signInWithPopup } from "firebase/auth";
const signIn = () =>{
console.log("logging");
const provider = new GoogleAuthProvider();
signInWithPopup(auth, provider)
.then((result) => {
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// IdP data available using getAdditionalUserInfo(result)
// ...
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.customData.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});
}
// This is my firebase.js file where configuration is done
const app = getApps().length > 0 ? getApp() : initializeApp(firebaseConfig);
const db = getFirestore();
const storage = getStorage();
const auth = getAuth(app);
export {app,db,storage,auth}`your text`
I have enabled the google sign-in method in firebase.
And since it already had localhost as an authorized domain.
It was working perfectly with next auth but is having a problem when I tried with firebase auth.

i don't know how to login with google and facebook in firebase

I wanted make a login using facebook and google accounts, this is my code:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
import { getAuth, createUserWithEmailAndPassword, signOut, signInWithEmailAndPassword,
onAuthStateChanged, GoogleAuthProvider, signInWithPopup } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js";
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
// login with google
const provider = new GoogleAuthProvider();
const signInWithGoogle = document.querySelector('#google-icon');
signInWithGoogle.addEventListener('click', (e) => {
e.preventDefault();
signInWithPopup(auth, provider).then((result) => {
const user = result.user;
const credential = GoogleAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
const email = error.email;
const credential = GoogleAuthProvider.credentialFromError(error);
});
});
but i keep getting this error message:
Info: The current domain is not authorized for OAuth operations. This will prevent signInWithPopup, signInWithRedirect, linkWithPopup and linkWithRedirect from working. Add your domain (127.0.0.1) to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.
can you help me, please?

invalid grant pops up while sending Gmail in nodemailer

When I send mail then, it successfully sends the mail. But after a few days, it says 'invalid_grant'. Then when I again generate a new refresh token from https://developers.google.com/oauthplayground and use it, it works again. So what's the problem that access token doesn't work after few days.
const GOOGLE_CLIENT_ID = process.env.GOOGLE_CLIENT_ID
const GOOGLE_CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET
const GOOGLE_REDIRECT_URI = process.env.GOOGLE_REDIRECT_URI
const GOOGLE_REFRESH_TOKEN = process.env.GOOGLE_REFRESH_TOKEN
const oAuth2Client = new google.auth.OAuth2(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REDIRECT_URI)
oAuth2Client.setCredentials({refresh_token: GOOGLE_REFRESH_TOKEN})
export async function sendMail(payload: IMailDTO): Promise<SMTPTransport.SentMessageInfo>{
const data = MailDTO.receiver(payload)
const accessToken = await oAuth2Client.getAccessToken()
const transport = nodemailer.createTransport({
// #ts-ignore
service: 'gmail',
auth: {
type: 'OAUTH2',
user: 'user#gmail.com',
clientId: GOOGLE_CLIENT_ID,
clientSecret: GOOGLE_CLIENT_SECRET,
refreshToken: GOOGLE_REFRESH_TOKEN,
accessToken,
}
})
const mailOptions = {
from: 'no-reply <no-reply#gmail.com>',
to: data.to,
subject: data.subject,
text: data.text,
html: data.html
}
let result = await transport.sendMail(mailOptions)
if(!result){
throw new Error("Email not sent. Try again.")
}
return result
}
The issue is not with your access token the issue is with your refresh token.
The first is the OAuth Playground will automatically revoke refresh tokens after 24h. You can avoid this by specifying your own application OAuth credentials using the Configuration panel.
The second being that if you have supplied your own OAuth Credentials and your application is still in testing then it will expire after seven days.
A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testing" is issued a refresh token expiring in 7 days.
To have a refresh token that will not expire you need to create it using your own credentials and make sure to set your application in production.

AWS - Get user token from an existing Cognito User Pool with username and password on an existing React web app

I have a simple React web app created from create-react-app.
I also have an existing user pool (set up by a third party) on Amazon Cognito. I have been given a username and password for authentication. Once authenticated, Cognito provides a JWT token.
What I want to achieve is to authenticate the user and get a JWT access_token within the componentDidMount method of the App component; then use the token to call other APIs to retrieve some data and then show the data on the App component.
The following info is known:
region
USER_POOL_ID
APP_CLIENT_ID
USER_ACCOUNT
USER_PASSWORD
AWS provides the authenticate_and_get_token function for Python developers. Is there an equivalent for JavaScript and React developers? Any sample code is appreciated.
Don't know about the authenticate_and_get_token you mentioned, couln't find this function in Boto3 docs.
But I do know different function to retrieve a token called adminInitiateAuth. This is function available for JS.
you can implement this using Lambda, like this:
const AWS = require('aws-sdk');
const USER_POOL_ID = "us-east-1_*******";
const APP_CLIENT_ID = "***********";
const USER_ACCOUNT = "***********";
const USER_PASSWORD = "***********";
const cognitoClient = new AWS.CognitoIdentityServiceProvider({
apiVersion: "2016-04-19",
region: 'us-east-1'
});
exports.handler = async (event) => {
try {
const userData = await userSignIn(USER_ACCOUNT, USER_PASSWORD);
return userData // refer to userData.AuthenticationResult.IdToken;
} catch(e){
throw e;
}
};
const userSignIn = async (username, password) => {
try {
var params = {
AuthFlow: 'ADMIN_NO_SRP_AUTH',
ClientId: APP_CLIENT_ID ,
UserPoolId: USER_POOL_ID,
AuthParameters: {
USERNAME: username,
PASSWORD: password
}
};
return await cognitoClient.adminInitiateAuth(params).promise();
} catch (err) {
return err.message ? err : {message : err};
}
};
Please make sure you have the specific permission to invoke this method, like "Action": "cognito-idp:AdminInitiateAuth", in the lambda permissions, or in IAM role.

How to create “credential” object needed by Firebase web user.reauthenticate() method?

var user = firebase.auth().currentUser;
var credential;
// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential).then(function() {
With the v3 Firebase client, how should I create this credential object for Google auth provider (Not email & Password).
How to do it with email and password was answered here: Email&Password.
I've tried var credential = firebase.auth.GoogleAuthProvider.credential(); but according to the docs it's needs an "Google Id Token" which I have no idea how to get.
You can create an AuthCredential by using firebase.auth.EmailAuthProvider.credential.
Then you can reauthenticate with firebase.User.reauthenticateWithCredential.
var user = firebase.auth().currentUser;
var credential = firebase.auth.EmailAuthProvider.credential(
user.email,
'yourpassword'
);
user.reauthenticateWithCredential(credential);
You can reauthenticate users that use GooglaAuth Provider without tokens and credentials using reauthenticateWithPopup(provider) or reauthenticateWithRedirect(provider) method:
// Create provider as usual
function createGoogleProvider() {
const provider = new auth.GoogleAuthProvider()
provider.addScope('profile')
provider.addScope('email')
return provider
}
// Reauthenticate with popup:
user.reauthenticateWithPopup(createGoogleProvider()).then(function(result) {
// The firebase.User instance:
var user = result.user;
}, function(error) {
// An error happened.
});

Categories