Building a simple application using the examples on their github page. I can log into my application using Cognito. What I can not do is logout because no matter what I try I can't get a hold of the user object. I've dorked around with various other calls to no avail (found here on their API page). The only other post on SO I found isn't applicable because I'm not using Federated Identity. The code I'm using is pretty much verbatim what's on the github page, but will post here for convenience:
login code:
var userName = $('#user_name_login').val();
var userPassword = $('#user_password_login').val();
var userData = {Username: userName, Pool : userPool};
var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
var authenticationData = {Username : userName, Password : userPassword};
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
// now that we've gotten our identity credentials, we're going to check in with the federation so we can
// avail ourselves of other amazon services
//
// critical that you do this in this manner -- see https://github.com/aws/amazon-cognito-identity-js/issues/162
// for details
var loginProvider = {};
loginProvider[cognitoCredentialKey] = result.getIdToken().getJwtToken();
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: identityPoolId,
Logins: loginProvider,
});
// //AWS.config.credentials = AWSCognito.config.credentials;
// AWSCognito.config.credentials = AWS.config.credentials;
// //call refresh method in order to authenticate user and get new temp credentials
// AWS.config.credentials.refresh((error) => {
// if (error) {
// alert(error);
// } else {
// console.log('Successfully logged in!');
// }
// });
// this is the landing page once a user completes the authentication process. we're getting a
// temporary URL that is associated with the credentials we've created so we can access the
// restricted area of the s3 bucket (where the website is, bruah).
var s3 = new AWS.S3();
var params = {Bucket: '********.com', Key: 'restricted/pages/user_logged_in_test.html'};
s3.getSignedUrl('getObject', params, function (err, url) {
if (err) {
alert(err);
console.log(err);
}
else {
console.log("The URL is", url);
window.location = url;
}
});
},
mfaRequired: function(session){
new MFAConfirmation(cognitoUser, 'login');
},
onFailure: function(err) {
alert("err: " + err);
},
});
I'm attempting to logout by executing:
userPool.getCurrentUser().signOut();
Note that the userPool and such are defined in another file, and is initialized thusly:
var poolData = {
UserPoolId : '*****',
ClientId : '*****'
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
so how do I sign my users out of the application?
closing this as the issue, as stated here, turned out to be a red herring. if you're doing what I was trying to do above in using cognito to generated a signed url to access an html file located in a restricted 'folder' in the bucket and you want to be able to logout from that new window location, make sure the signed url is of the same domain as your landing page.
for example, if you land at foo.com because you've got an A or CNAME DNS record set up so that your users don't have to hit a doofy cloudfront or s3 generated url in order to get to your website, you need to make sure you ALSO generate a signed URL that has the same domain name. Otherwise you won't be able to access the bucket. Moreover - you won't be able to access your user object because the session object is keyed to a different domain name than the one you're currently at.
see this for information on how to specify what the domain of the signed url should be.
and also note that there's a lot of trouble you can get into if you are using a third-party domain registar. I just burned two weeks unborking myself because of that :-/
Related
I already deploy a static web site use AWS S3 and use AWS cognito to handle User Sign in.
The web Site is https://www.tianboqing.com
The HTML page have a Button,When user Click the button,the url will redirect to cognito sign in url.
'https://tianboqing.auth.us-east-1.amazoncognito.com/login?
client_id=4fgb77l991egfiubejfqep3e6e&response_type=token&scope=aws.cognito.signin.user.admin&redirect_uri=https://www.tianboqing.com';
const handleClick = (event) => {
window.location.href =
'https://tianboqing.auth.us-east-1.amazoncognito.com/login?...
};
document.querySelector('button').addEventListener('click', handleClick);
When User sign In,The Cognito will return a new url like this:
https://www.tianboqing.com/#access_token=eyJraWQiOiJrNFdXeWpRZXZiSlwvN3JNRUlVMzFHS0p4YmtBZHpXMExwN0xMT0tiS1BHRT0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI2ZmNiNTZhOS1kNDhmLTQyYzItYWUyMi1hMzk0NTllNzc5ZDIiLCJ0b2tlbl91c2UiOiJhY2Nlc3MiLCJzY29wZSI6ImF3cy5jb2duaXRvLnNpZ25pbi51c2VyLmFkbWluIiwiYXV0aF90aW1lIjoxNjM1MzAyMDIxLCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAudXMtZWFzdC0xLmFtYXpvbmF3cy5jb21cL3VzLWVhc3QtMV9Zcm9BY0h5R20iLCJleHAiOjE2MzUzMDU2MjEsImlhdCI6MTYzNTMwMjAyMSwidmVyc2lvbiI6MiwianRpIjoiM2EyMjg0YjItNGM2MS00ZDcyLTk4NGYtNzIzNTExMDc3YmZlIiwiY2xpZW50X2lkIjoiNGZnYjc3bDk5MWVnZml1YmVqZnFlcDNlNmUiLCJ1c2VybmFtZSI6IjZmY2I1NmE5LWQ0OGYtNDJjMi1hZTIyLWEzOTQ1OWU3NzlkMiJ9.xKToMEhhSCqSy9ip0ikmdezY9XRz0GIlIdESSThEuLabWL4rFTw1XRQi4Z9OeDLZcmHyemZt0A1o1OvqZLFyrEHLmRAoyg5SIGD2Ic6tExS1PAmmX8Fe3uF7f851DtKMeapxsaNYyaLE3v-_vkJkDwRvUNoz8nOMUCYB3JKJxGPBlMz1yfn-3CXejepKLYeYYDOUaCPmyErfCy84_eQ-ZoEZFd3bH4vZXDNJKFj6W5_C4IZHuIAJveep3dYVq9cLWy3m8BWOAKWVxk6jTt1w0xI5og5jJiEIPn8Ok10WL1s4eEzAN04AYj6e05uzw4Ka_ip4y7VCdnndnTuWAx_5wQ&expires_in=3600&token_type=Bearer
Which contain the access_token to parse.
My question is,How the code can know the new url which contain access_token is return.
Do I need front route or async await or something?
const handleClick = (event) => {
window.location.href =
'https://tianboqing.auth.us-east-1.amazoncognito.com/login?client_id=...';
};
How to get the user token so I can use it to post to dynamodb?
I will suggest to use API Gateway, where you can add Cognito Authorizer for each and every API you deploy to interact with DynamoDB.
Here is the official documentation you can go through to setup your API-Gateway with Cognito, that you want to use to save records in DynamoDB.
You can grab that access token from the Cognito return page and save it as Session Storage in the front-end using JavaScript.
window.sessionStorage.setItem("accessToken", YourAccessToken);
Use the above stored accessToken as Authorization Header when you call that API via AJAX.
var tok = window.sessionStorage.getItem("accessToken")
var xhr = new XMLHttpRequest();
xhr.open("POST", "URL");
xhr.setRequestHeader("Authorization", tok);
xhr.send();
Instead of url forwarding, you can use AWS-Cognito javascript SDK and use Javascript (via AJAX) to authorize a user.
var cognitoUser = new AmazonCognitoIdentity.CognitoUser({
Username: username,
Pool: userPool
});
var authenticationData = new AmazonCognitoIdentity.AuthenticationDetails({
Username: username,
Password: password
});
cognitoUser.authenticateUser(authenticationData, {
onSuccess: function (result) {
// your code here on success
},
onFailure: function (err) {
// your code here if error occurs
}
});
I want to fetch the authentication tokens from AWS;
however, I only receive an error telling me
that the client id is not correct.
I was very happy to have found this code on the web,
link: https://docs.aws.amazon.com/cognito/latest/developerguide/authentication.html
and I was able to invoke the last function call,
but it complains about the ClientId, and I have no clue
where to fetch the Clientid from :-(
I am not sure from where to fetch the Client Id and User Pool Id from?
There is also a Client App Id on the AWS web site.
I am looking for something where I only have to provide
the userid and password using node js?
const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
var authenticationData = {
Username : '...',
Password : '...',
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = {
UserPoolId : '...', // From where on the AWS web site can I fetch the correct User Pool Id?
ClientId : '...' // From where on the AWS web site can I fetch the correct client Id?
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username : 'karlschmitt',
Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
var accessToken = result.getAccessToken().getJwtToken();
/* Use the idToken for Logins Map when Federating User
Pools with identity pools or when passing through an
Authorization Header to an API Gateway Authorizer */
var idToken = result.idToken.jwtToken;
console. log("Successful!");
},
onFailure: function(err) {
// alert(err);
console. log("Failure!" + err.message);
},
});
Create Congnito User Pool - Here is a link and grab Pool Id from General Settings
Register your application as a Client - Here is a link and grab client id
My problem:
Using AWS SDK to invoke an AWS Lambda is giving me config errors
CredentialsError: Missing credentials in config
What I found:
Loggin in a user for the first time initiates proper config settings, but it's lost upon page refresh.
The Goal:
Use...the code below, even after the user has refreshed the page
lambda.invoke(params, function(err, data) {
if (err) {
// console.log(err, err.stack);
} else {
console.log(data);
} // successful response
});
Below is how I signIn a user from a cognitoUserPool the 1st time
Step 1 capture username and password
trySignIn(username, password) {
console.log("trying to sign in");
var authenticationData = {
Username: username,
Password: password
};
Step 2 use new AmazonCognitoIdentity.AuthenticationDetails
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(
authenticationData
);
Step 3 configure UserPool with UserData
var poolData = {
UserPoolId: "myPoolId", // Your user pool id here
ClientId: "myPoolClient" // Your client id here
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username: username,
Pool: userPool
};
Step 4 Get a CognitoUser object
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result) {
var accessToken = result.getAccessToken().getJwtToken();
console.log(result);
//POTENTIAL: Region needs to be set if not already set previously elsewhere.
//AWS.config.region = "us-east-1"; //moved to component did mount
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: "myidentiy-id-pool-id", // your identity pool id here
Logins: {
// Change the key below according to the specific region your user pool is in.
"cognito-idp.us-east-1.amazonaws.com/us-east-1": result
.getIdToken()
.getJwtToken()
}
});
Step 5 Here we can configure the AWS SDK to use things like AWS.Lambda / AWS.S3
//refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
AWS.config.credentials.refresh(error => {
if (error) {
console.error(error);
} else {
// Instantiate aws sdk service objects now that the credentials have been updated.
// example: var s3 = new AWS.S3();
console.log("Successfully logged!");
}
});
Problem is event after saving the UserObject to storage I lose the AWS.config information and I can't reconfigure it without asking for the users password everytime
var user = { username: username };
localStorage.setItem("cognitoUser", JSON.stringify(user));
console.log(cognitoUser);
console.log(user);
The Question ?
How can I configure AWS.config having only access to the cognitoUser Object from storage, but not the user password
Update: <-- Did Not Work
I'm thinking it might be possible to save the variable created in Step 5 to storage.
var lambdaTry = new AWS.Lambda
localStorage.setItem("lambdaTry", JSON.stringify(lambdaTry));
I'm trying to update a user's attribute right after authentication.
Auth works fine and I'm able to retrieve user attributes with it.
But the problem is var cognitoUser = getUserPool().getCurrentUser(); returns null. How do I retrieve the current user so that I am able to update the attribute but without refreshing the browser?
Perhaps another question would be, how do I use the accessToken to run functions on the current user without refreshing the browser?
var cognitoUser = getUserPool().getCurrentUser();
if (cognitoUser != null) {
cognitoUser.getSession(function(err, session) {
if ( err ) {
console.log(err);
return;
}else if( session.isValid() ){
updateUserAttribute( cognitoUser, 'custom:attr', attr )
}
});
}else{
console.log('Cognito User is null');
return;
}
getUserPool().getCurrentUser() looks for the user on the local storage, if it returns null is because the local storage do not have an user already set.
To setup the user on the local storage I use an instance of CognitoAuth that makes the job.
This solution is using Cognito Hosted UI.
On the callback url that is returned by Cognito UI:
Then, if you call getUserPool().getCurrentUser() this will not be null.
import { CognitoAuth } from "amazon-cognito-auth-js"
const authData = {
UserPoolId: "us-east-1_xxxxxx",
ClientId: "xxxxxxx",
RedirectUriSignIn: "https://examole.com/login",
RedirectUriSignOut: "https://example.com/logout",
AppWebDomain: "example.com",
TokenScopesArray: ["email"]
}
const auth = new CognitoAuth(authData)
auth.userhandler = {
onSuccess: function(result) {
//you can do something here
},
onFailure: function(err) {
// do somethig if fail
}
}
//get the current URL with the Hash that contain Cognito Tokens tokens
const curUrl = window.location.href
//This parse the hash and set the user on the local storage.
auth.parseCognitoWebResponse(curUrl)
Then, if you call getUserPool().getCurrentUser() this will not be null.
var cognitoUser = getUserPool().getCurrentUser();
That should return the last authenticated user, if the user pool is initialized correctly. Upon a successful authentication, we save the user keyed on the client id to local storage. Whenever you call getCurrentUser, it will retrieve that particular last authenticated user from local storage. The tokens are keyed on that user and client id. They are also saved to local storage after a successful authentication. Accessing the access token should be just:
cognitoUser.getSignInUserSession().getAccessToken().getJwtToken())
and you can use the token directly with the operations exposed in the CognitoIdentityServiceProvider client.
This is a fairly old question, so you may have moved on by now, but I think you need to create the user pool, using your userpoolId and clientID. I don't think you can just call getUserPool() without those being known and/or somehow available in memory. For example:
function makeUserPool () {
var poolData = {
UserPoolId : "your user pool id here",
ClientId : "you client id here"
};
return new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
}
var userPool = makeUserPool();
var currAWSUser = userPool.getCurrentUser();
I'm getting Invalid access key error using credentials redeemed from an amazon open id token from cognito
Here's what I'm doing
Get developer authenticated open id token
cognito.getOpenIdTokenForDeveloperIdentity(params, function (err, data) {
openIdToken = data.credentials
});
Redeem open id token for security credentials, I set the params to the congnito Auth role and set an arbitrary role session name. I use the token from step 1. There is no place where I set the identity id from step 1.
it('should be able to exchange temporary open id token for auth credentials', function (done) {
var sts = new AWS.STS();
var params = {
RoleArn: roleArn,
RoleSessionName: 'photo-upload-session',
WebIdentityToken: openIdToken.Token
};
sts.assumeRoleWithWebIdentity(params, function(err, data) {
should.not.exist(err);
should.exist(data.Credentials.AccessKeyId);
should.exist(data.Credentials.SecretAccessKey);
should.exist(data.Credentials.SessionToken);
credentials = data.Credentials;
done();
});
});
I update the current credentials
AWS.config.update({accessKeyId : credentials.AccessKeyId, secretAccessKey:credentials.SecretAccessKey});
I upload a file to s3 and get the [InvalidAccessKeyId: The AWS Access Key Id you provided does not exist in our records.] error
*edit using Bob Kinney's advice I tried two methods - setting the sessionToken (which worked) and using the Congito credentials which gave a TypeError not a buffer error. The CognitoIdentityCredentials example is below.
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId:config.get('aws_identity_pool_id'),
Logins: {
'cognito-identity.amazonaws.com': openIdToken.Token
}
});
var body = fs.createReadStream(__dirname + '/test_photo.jpg');
var s3obj = new AWS.S3({params: {Bucket: 'test-uploads', Key: 'test'}});
s3obj.upload({Body: body}).
on('httpUploadProgress', function(evt) { console.log(evt); }).
send(function(err, data) {
should.not.exist(err);
done();
});
** update
So moving back to the java client error, we are using the openid token (which was tested to be working correctly with the sts.assumeRoleWithWebIdentity) and passing that token into an extension of AWSAbstractCognitoIdentityProvider (code taken from this link http://docs.aws.amazon.com/cognito/devguide/identity/developer-authenticated-identities/) - then using that identity to upload to s3 getting the error
CustomAwsIdentityProvider provider = CustomAwsIdentityProvider.newInstance(this, BuildConfig.AWS_COGNITO_POOL_ID, Regions.US_EAST_1);
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(this, provider, Regions.US_EAST_1);
TransferManager tm = new TransferManager(credentialsProvider);
tm.upload("my-upload", uuid.toString(), file);
Sorry for the issues. It appears you are using the JavaScript SDK. When using this flow you can use the standard AWS.CognitoIdentityCredentials object as mentioned in the developer guide using the key of cognito-identity.amazonaws.com and the value as the OpenId Connect token returned from the getOpenIdTokenForDeveloperIdentity call.
The reason for the error you are seeing is that you are not including the sessionToken from the STS result. Using the AWS.CognitoIdentityCredentials object should resolve this for you.
Update 2015-07-21: There is a small issue in the SDK that will unfortunately prevent AWS.CognitoIdentityCredentials from working as I described it. We are working on mitigating this issue.
Update 2015-07-24: You should be able to use the following to use the AWS.CognitoIdentityCredentials with your developer authenticated identiity:
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'MY_IDENTITY_POOL',
IdentityId: data.IdentityId,
Logins: {
'cognito-identity.amazonaws.com': data.Token
}
});
Where data is the response from GetOpenIdTokenForDeveloperIdentity.