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.
});
Related
I am using aws cognito service for authentication, followed https://github.com/aws-amplify/amplify-js/tree/master/packages/amazon-cognito-identity-js this documentation.
My login flow is something like this:
import {AuthenticationDetails,CognitoUser,CognitoUserPool} from 'amazon-cognito-identity-js';
const authenticationData = {
Username: <username>,
Password: <password>
};
const authenticationDetails = new AuthenticationDetails(
authenticationData
);
const userData = {
Username: <username>,
Pool: <userPoolId>,
};
const cognitoUser = new CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: (result) => {
const accessToken = result.getAccessToken().getJwtToken();
console.log('access token --> ', accessToken);
},
onFailure: (err) => {
console.log("error",err.message);
},
mfaRequired: function (codeDeliveryDetails) {
var verificationCode = prompt('Please input verification code', '');
cognitoUser.sendMFACode(verificationCode, this);
},
})
I've already created one AWS Cognito UserPool and the enabled MFA for the same.
In signin flow is working and the user is authenticated by multi-factor-authentication and I'm getting the access token.
But now I want not to verify mfa for the same device multiple times. Something like remember the device for the specific user for new 10-15 logins or next 7-15 days.
I checked the docs and seemed I can achieve this with aws amplify.
async function rememberDevice() {
try{
const result = await Auth.rememberDevice();
console.log(result)
}catch (error) {
console.log('Error remembering device', error)
}
}
But aws amplify is not working for me as it has an open issue.
https://github.com/aws-amplify/amplify-js/issues/9204
In my cognito user pool I tried to set this one, but it's not helping as well.
Is there any other option available in Cognito api to achieve my requirement?
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);
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.
I'm making an user management with the cognito Amazon Webservice.
I already manage the signing to my userPool but everyTime I'm trying to login to my user pool I've this console error :
Error: this.pool.getUserPoolId is not a function
I don't know where is from getUserPoolId...
EDIT: I've my login function in a factory that's my code :
login: function(username, password) {
var authenticationData = {
Username : username,
Password : password
};
var userData = {
Username :username,
Pool : poolData
};
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
/*Use the idToken for Logins Map when Federating User Pools with Cognito Identity or when passing through an Authorization Header to an API Gateway Authorizer*/
console.log('idToken + ' + result.idToken.jwtToken);
},
onFailure: function(err) {
alert(err);
},
});
}
Does anyone know what to do ?
The AWS Cognito JavaScript SDK initialization pattern requires that you pass "data objects" to an AWS SDK constructor. In return, the SDK gives you back an AWS "interface" with various connection methods.
I think from your code you used the data object instead of the subsequent interface.
Example:
// Data Object used for initialization of the interface
const userPoolData = {
UserPoolId: identityPoolId,
ClientId: clientId
}
// The `userPoolInterface`, constructed from your `poolData` object
const userPoolInterface = new AWSCognito
.CognitoIdentityServiceProvider
.CognitoUserPool(userPoolData)
In the code you provided, it seems you are passing the userData object (used for initialization), where you should be passing the userPool interface that should have been previously initialized.
Try this instead:
login: function(username, password) {
// 1) Create the poolData object
var poolData = {
UserPoolId: identityPoolId,
ClientId: clientId
};
// 2) Initialize the userPool interface
var userPool = new AWSCognito
.CognitoIdentityServiceProvider
.CognitoUserPool(poolData)
// 3) Be sure to use `userPool`, not `poolData`
var userData = {
Username : username,
Pool : poolData, // <-- Data?! Oops..
Pool : userPool // "interface", that's better :)
};
var authenticationData = {
Username : username,
Password : password
};
var cognitoUser = new AWSCognito
.CognitoIdentityServiceProvider
.CognitoUser(userData)
var authenticationDetails = new AWSCognito
.CognitoIdentityServiceProvider
.AuthenticationDetails(authenticationData);
cognitoUser.authenticateUser( ...etc... );
}
Try it online:
If it helps, I am taking notes and making examples, while I walk through the AWS Cognito SDK examples. You are welcome to checkout the Github repo I am using. It might help if you can test out a working example.
Github Repository
/ Live Demo
I assume you are initializing your poolData object:
var poolData = {
UserPoolId : '...', // Your user pool id here
ClientId : '...' // Your client id here
};
So I am messing around with Cognito and their Beta User Pools feature in Javascript. I am successfully creating users thanks to the documentation found here:
http://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html
When I try and authenticate the users though I get a strange error message saying:
NotAuthorizedException: Incorrect username or password.
I don't understand why this is the case as I am literally copying and pasting the values for userName and password that I used to create the user, which is working fine.
Below is my code to authenticate the user:
//----- Setup
AWS.config.region = 'us-east-1'; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'myIdentityPoolId'
});
AWSCognito.config.region = 'us-east-1';
AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'myIdentityPoolId'
});
var poolData = { UserPoolId : 'myUserPoolId',
ClientId : 'myClientId'
};
//-----Authenticate a user
alert('Authenticate a user with application');
var authenticationData = {
Username : 'markie17061993',
Password : 'MeowWoof123456789!',
};
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
var poolData = { UserPoolId : 'myUserPoolId',
ClientId : 'myClientId'
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var userData = {
Username : 'markie17061993',
Pool : userPool
};
var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
alert('hiss');
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('access token + ' + result.getAccessToken().getJwtToken());
},
onFailure: function(err) {
alert(err);
},
});
Do you see anything wrong here? I thought perhaps my UserName parameter in these two places is meant to be a different value or something:
var authenticationData = {
Username : 'markie17061993',
Password : 'MeowWoof123456789!',
};
var userData = {
Username : 'markie17061993',
Pool : userPool
};
Thanks
Your code doesn't show if you are confirming the newly signed up user not. If you are not, that would explain the NotAuthorizedException. This example specifically is what you want to follow.
If you do not want to confirm the users being signed up from you app, you should use a PreSignUp trigger to autoConfirm your users.