AWS Amplify - Disable Current User Account - amazon-web-services

AWS Amplify Authentication module has some methods for actions like sign in, sign up, forgot password etc. Even one can let the user to update his/her info through like:
import { Auth } from 'aws-amplify'
// Auth API Sign-in sample
Auth.signIn(username, password)
.then(user => console.log(user))
.catch(err => console.log(err))
// Auth API Change info sample
let result = await Auth.updateUserAttributes(user, {
'email': 'me#anotherdomain.com',
'family_name': 'Lastname'
})
However, I could not see anyway to disable (beware, not to delete) an account.
So, a user can sign up to a web application, but cannot deactivate it using AWS Amplify? If not, are there any other ways for disabling an AWS Cognito User Pool user via Javascript code?

I went through the AWS Documentation for the Cognito User Pools API and found some methods that let a function with admin privileges disable(not delete) a Cognito User Pool account!
Here is the link to the documentation on the AWS website:
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminDisableUser.html
There is also a method to reenable the user:
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminEnableUser.html
The javascript implementation for this can be found here:
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CognitoIdentityServiceProvider.html#adminDisableUser-property
The code would be something like this using the AWS SDK for JS:
var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});
var params = {
UserPoolId: 'STRING_VALUE', /* required */
Username: 'STRING_VALUE' /* required */
};
cognitoidentityserviceprovider.adminDisableUser(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});

Related

AWS amplify cognito accessing pubsub with AccessToken, IdToken and RefreshToken

I am using AWS amplify with Angular and I followed the instructions to setup Amplify, add backend and then auth.
I also created a user in cognito pool and used it to login in my angular app. I am able to see AccessToken, IdToken and RefreshToken in the browser network tab. As per the guide I have to use these to obtain the pool tokens using which I can get temporary aws credentials to access aws services. I want to access pubsub to show messages being sent to aws iot_core.
But I was unable to find any information of how exactly we use these 3 tokens to access AWS resources..? Can anybody shed some light on this?
async signIn() {
Auth.signIn('xxxxx', 'xxxxx')
.then(user => {
if (user.challengeName === 'NEW_PASSWORD_REQUIRED') {
const { requiredAttributes } = user.challengeParam; // the array of required attributes,
e.g ['email', 'phone_number']
Auth.completeNewPassword(
user, // the Cognito User Object
'xxx', // the new password
// OPTIONAL, the required attributes
{
email: 'xxxx#example.com',
}
).then(user => {
// at this time the user is logged in if no MFA required
console.log(user);
}).catch(e => {
console.log(e);
});
} else {
console.log("Connecting to AWS IoT...")
//Apply plugin with configuration
Amplify.addPluggable(new AWSIoTProvider({
aws_pubsub_region: 'us-east',
aws_pubsub_endpoint: 'wss://xxxxx-ats.iot.us-east-1.amazonaws.com/mqtt',
}));
console.log("hello")
}
}).catch(e => {
console.log(e);
});
}
As per the Amplify docs on PubSub you have to:
Create IAM policies for AWS IoT
Attach your policy to your Amazon Cognito Identity
Allow the Amazon Cognito Authenticated Role to access IoT Services
https://docs.amplify.aws/lib/pubsub/getting-started/q/platform/js/#step-1-create-iam-policies-for-aws-iot

How to parse JWT Token after user Sign In AWS Cognito

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

AWS Cognito Error: No Cognito Identity pool provided for unauthenticated access

var normalAuth = async (username, password) => {
try{
var user = await Auth.signIn(username, password)
console.log(user)
if(user.challengeName === "NEW_PASSWORD_REQUIRED"){
console.log("assigning new password!")
user = await Auth.completeNewPassword(user, "password") // give the user a new password. this would NOT be included in any kind of production code, its only here as a work around
console.log(user)
} // work around. users created in the console are only given temporary passwords, and as such have no authorization
// setting a new password will fix this
console.log(await Auth.currentCredentials()) // THIS THROWS AN ERROR?!?!
setAuthState(false) // auth is no longer in progress
}
catch(error){
console.error(error)
}
}
I'm trying to grab the tokens from my Amplify user after authenticating but I'm receiving the error
No Cognito Identity pool provided for unauthenticated access
This is pretty strange because I'm not using an identity pool at all. My baseline assumption was that I shouldn't need to provide an identity pool ID at all in my amplify config.
config looks like this
var amplifyConfig = {
Auth: {
mandatorySignIn: false,
region: "us-east-1",
userPoolId: "mypoolid",
userPoolWebClientId: "myclientid"
}
}
The really weird part is that the tokens are actually there in user after I authenticate. It's only when I try and retrieve them this way specifically that an error is thrown.
Any idea what's going on here?

Why is my AWS Congito user able to sign in, but "not authenticated" when using Auth.currentAuthenticatedUser()?

I have manually added an AWS Cognito user to my application's user pool via the AWS management console. The required user pool credentials have been confirmed for this user. I am setting up an auth guard to control access to the routes. Whenever I use the Auth.signIn() function, the promise resolves successfully, however, when calling Auth.currentAuthenticatedUser() after signing in, the promise within the canActivate() function returns an error message "not authenticated". I have read GitHub issues on cookieStorage causing issues with this, but do not have this configured.
sign-in.component.ts
signIn(username, password) {
return new Promise(() => {
Auth
.signIn(username, password)
.then(() => {
this.router.navigate(['main/dashboard']); // navigates to main/dashboard as expected
})
.catch(err => {
this.authenticationError = err.message;
})
});
}
auth.guard.ts
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return Auth
.currentAuthenticatedUser()
.then(() => {
return true;
})
.catch((err) => {
this.router.navigate(['signin']);
console.log(err) // "not authenticated"
return false;
});
}
Users created via the AWS management console are not considered authenticated unless the status field for that user is CONFIRMED. The status field in my case was FORCE_CHANGE_PASSWORD. AWS expects that users created via the console change their password after the first sign in or verify their account using an email or mobile verification. In the case of my app, I did not want to use either email or mobile verification. To resolve this I used the following aws-cli command for that user.
aws cognito-idp admin-set-user-password --user-pool-id your_user_pool_id --username username --password password --permanent
I was facing this issue also after signing up, but it turns out you also need to log the user in too after you verify email with the code.
For example:
Auth.signUp
Auth.confirmSignUp
Auth.signIn
For more info https://docs.amplify.aws/lib/auth/emailpassword/q/platform/js

Cognito auth flow fails with "Already found an entry for username Facebook_10155611263153532"

The goal is to implement a social provider auth flow as described in User Pools App Integration and Federation.
One important thing that I want to satisfy, is to merge user pool accounts that have the same email address.
I am accomplishing that by calling adminLinkProviderForUser within the PreSignUp_ExternalProvider cognito lambda trigger.
So with this, everything works. The new social provided user is being registered and linked with the already existing Cognito (user+pass) user.
However, the authentication flow, from user's perspective doesn't complete. It fails at the last step where the callback uri (defined in cognito user pool) is being called:
error: invalid_request
error_description: Already found an entry for username Facebook_10155611263152353
But then, if the user retries the social auth flow, everything works, and would get session tokens that represent the original Cognito User Pool user (the one that already had that email).
Note that I'm testing the auth flow on an empty User Pool, zero user accounts.
For all the poor souls fighting with this issue still in 2020 the same way I did:
I have eventually fixed the issue by catching the "Already found an entry for username" in my client application and repeating the entire auth flow once more.
Luckily the error only gets fired on the initial external provider signup but not in the subsequent signins of the same user (cause it happens during signup trigger, duh).
I'm taking a wild guess, but here is what I think is happening:
In my case, the facebook provider was getting succesfully linked with
the pre-existing cognito email/password user. new Facebook userpool
entry linking to the email/password user was succesfully created.
Still, it seems
like cognito tried to register the fully isolated Facebook_id user
during the internal signup process (even though a link user entry with the same username was already created in the previous step). Since the "link user" with the
username Facebook_id was already existing, cognito threw an
"Already found an entry for username Facebook_id error" internal error.
This error has been repeatedly voiced over to the AWS developers since 2017 and there are even some responses of them working on it, but in 2020, it's still not fixed.
Yes, this is how it is currently setup. If you try to link users using PreSignUp trigger, the first time won't work. A better way to handle this(I think) would be to provide an option in your UI to link external accounts on sign-in. In the pre-signup trigger, search for a user with the same unique attribute (say email) and see if the sign up is from external provider. Then show a message such as email already exists. Login in & use this menu/option to link. Haven't tested this though.
To elaborate on #agent420's answer, this is what I am currently using (Typescript example).
When a social identity attempts to sign up and the email address already exists I catch this using the PreSignUp trigger and then return an error message to the user. Inside the app, on the user's profile page, there is an option to link an identity provider which calls the adminLinkProviderForUser API.
import {
Context,
CognitoUserPoolTriggerEvent,
CognitoUserPoolTriggerHandler,
} from 'aws-lambda';
import * as aws from 'aws-sdk';
import { noTryAsync } from 'no-try';
export const handle: CognitoUserPoolTriggerHandler = async (
event: CognitoUserPoolTriggerEvent,
context: Context,
callback: (err, event: CognitoUserPoolTriggerEvent) => void,
): Promise<any> => {
context.callbackWaitsForEmptyEventLoop = false;
const { email } = event.request.userAttributes;
// pre sign up with external provider
if (event.triggerSource === 'PreSignUp_ExternalProvider') {
// check if a user with the email address already exists
const sp = new aws.CognitoIdentityServiceProvider();
const { error } = await noTryAsync(() =>
sp
.adminGetUser({
UserPoolId: 'your-user-pool-id',
Username: email,
})
.promise(),
);
if (error && !(error instanceof aws.AWSError)) {
throw error;
} else if (error instanceof aws.AWSError && error.code !== 'UserNotFoundException') {
throw error;
}
}
callback(null, event);
};
I finally got this thing working in a non-weird way where users have to authorize twice or other things.
Process explained:
User tries to authenticate using an identity provider, for the first time => PreSignUp lambda kicks in and check if user exists via email
1a. If the user exists, it will throw an error, eg. CONFIRM_IDENTITY_LINK_token that I'm capturing on the client.
token is a base64 string with the username and identity id ("username:facebook_123456")
1b. If the username does not exist, I create a new user with a temporary password and throw an error FORCE_CHANGE_PASSWORD_token. Same token but I add the temporary password to this time.
In the client I have one callback route '/authorize' => this is the one you set up as a callback URL in Cognito, and 2 extra routes: '/confirm-password' and '/configure-password'.
In the /authorize route I'm capturing the errors and getting the attached tokens and redirect to the extra routes: 1a => /configure-password?token=token and 1b => /confirm-password?token=token
For "/confirm-password" I ask the user to confirm its current password in order to authorize linking with the provider, then use the token to log him in with the identity id as clientMetadata, eg "{"LINK_PROVIDER": "facebbok_12345678"}"
On login, I have a PostAuthentication lambda which checks for the "LINK_PROVIDER" in the clientMetadata, and links it to the user.
For "/configure-password" I parse the token and do a "shallow" login with the credentials from the token and identity id as client metadata (same as above) then prompt the user to configure a new password for his account.
I know it might seem a little bit restrictive but I find it better than to authorize twice.
Also, this does not create extra users for identities in the user pool.
Code examples:
PreSignUp lambda
export async function handler(event: PreSignUpTriggerEvent) {
try {
const { userPoolId, triggerSource, request, userName } = event
if (triggerSource === 'PreSignUp_ExternalProvider') {
// Check if user exists in cognito
let currentUser = await getUserByEmail(userPoolId, request.userAttributes.email)
if (currentUser) {
// User exists, thow error with identity id
const identity = Buffer.from(`${currentUser}:${userName}`).toString('base64')
throw new Error(`CONFIRM_USER_IDENTITY_${identity}`)
}
// Create new Cognito user with temp password
const tempPassword = generatePassword()
currentUser = await createNewUser(userPoolId, request.userAttributes, tempPassword)
// Throw error with token
const state = Buffer.from(`${currentUser}:${tempPassword}:${userName}`).toString('base64')
throw new Error(`FORCE_CHANGE_PASSWORD_${state}`)
}
return event
} catch (error) {
throw new Error(error)
}
}
PostAuthentication lambda
export async function handler(event: PostAuthenticationTriggerEvent) {
try {
const { userPoolId, request, userName } = event
if (request.clientMetadata?.LINK_IDENTITY) {
const identity = request.clientMetadata['LINK_IDENTITY']
// Link identity to user
await linkIdentityProvider(userPoolId, userName, identity)
}
return event
} catch (error) {
console.error(error)
throw new Error('Internal server error')
}
}
We faced the same issue and tried various hacks to get around it. As we started to use SignInWithApple, we couldn't handle it with the 'double turnaround' because Apple always wants the user to enter their email and password, not like Google, where the second time, everything works automatically. So the solution we ended up building was to store the Cognito/IdP ID (Google_1234, SignInWithApple_XXXX.XXX.XXX) in our database but still create a native Cognito user that isn't linked via Cognito.
The native user is created to make unlinking easier because first, we get rid of the data (IdP user-id) we store in our database and then the Cognito IdP user. The user can then proceed using the Native Cognito user. Then we have a middleware component in place that allows us to have JWT in the external IdP or Cognito native format and translates so we can use both versions. As long as the user uses an IdP/SSO, we reset the Native users' password to a very long random value and prevent resetting it, so they must use the IdP.
So whatever you are trying to do, prevent using the admin-link-provider-for-user command!
The same code in JavaScript getUser has been called instead of listUsers. It is also assumed that all users have their email id as their username.
const aws = require('aws-sdk');
exports.handler = async (event, context, callback) => {
console.log("event" + JSON.stringify(event));
const cognitoidentityserviceprovider = new aws.CognitoIdentityServiceProvider({apiVersion: '2016-04-18'});
const emailId = event.request.userAttributes.email
const userName = event.userName
const userPoolId = event.userPoolId
var params = {
UserPoolId: userPoolId,
Username: userName
};
var createUserParams = {
UserPoolId: userPoolId,
Username: emailId,
UserAttributes: [
{
Name: "email",
Value: emailId
},
],
TemporaryPassword: "xxxxxxxxx"
};
var googleUserNameSplitArr = userName.split("_");
var adminLinkUserParams = {
DestinationUser: {
ProviderAttributeName: 'UserName',
ProviderAttributeValue: emailId,
ProviderName: "Cognito"
},
SourceUser: {
ProviderAttributeName: "Cognito_Subject",
ProviderAttributeValue: googleUserNameSplitArr[1],
ProviderName: 'Google'
},
UserPoolId: userPoolId
};
var addUserToGroupParams = {
GroupName: "Student",
UserPoolId: userPoolId,
Username: emailId
};
if (userName.startsWith("Google_")) {
await cognitoidentityserviceprovider.adminGetUser(params, function (err, data) {
if (err) {
console.log("No user present")
console.log(err, err.stack);
cognitoidentityserviceprovider.adminCreateUser(createUserParams, function (err, data) {
if (err) console.log(err, err.stack);
else {
console.log("User Created ")
cognitoidentityserviceprovider.adminAddUserToGroup(addUserToGroupParams, function (err, data) {
if (err) console.log(err, err.stack);
else {
console.log("added user to group");
console.log(data);
}
});
cognitoidentityserviceprovider.adminLinkProviderForUser(adminLinkUserParams, function (err, data) {
if (err) console.log(err, err.stack);
else {
console.log("user linked");
console.log(data);
}
});
console.log(data);
}
});
} else {
console.log("user already present")
cognitoidentityserviceprovider.adminLinkProviderForUser(adminLinkUserParams, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
console.log("userlinked since user already existed");
console.log(data);
}
});
console.log(data);
}
});
}
console.log("after the function custom");
callback(null, event);
};
This is a well know error. I handle it by retrying the request after this error and it will work. The error is because there is not way in the SDK to let it know to the pool that you already link the Federation Credentials to an user and it try to create a new user with those credentials
I wanted to have the feature of having a user seamlessly being able to login with one social provider (ex: Facebook) and then another one (Google).
I struggled with the retry process, especially with Google Login. At the signup process, if a user have several accounts, he will need to process twice the account selection.
What I ended up doing is just using Cognito for the client side code and token generation and have a lambda in the pre signup process mapping userIds with their email in a custom DB (Postgres or DynamoDB).
Then when a user query my API, based on their userId (whether it's a FacebookId or a cognito email userId, I am querying the DB to find the linked email and I am able to authenticate any users and their data like this.
Did this bug all of a sudden stop happening on 2/21/23? We didn't change anything but now this is no longer happening to users on their first time signing up. We also noticed that the UI for how Cognito is showing linked users is different - there is just 1 cognito account you're able to see in Cognito instead of multiple. You can still see the federated linked accounts in the identities property though