adminSetUserMFAPreference
not working as expected while trying to set/unset MFA for user in AWS Cognito
I had a use case in AWS Cognito where I had to set the MFA from the lambda functions using the adminSetUserMFAPreference
in AWS JavaScript SDK. It wasn’t working and there is an open issue on GitHub related to the same at the time of writing this post.
Interestingly, the same issue doesn’t exist in Python SDK. So as a workaround I wrote a Lambda function in Python and invoked the same from my JavaScript Lambda function for setting MFA.
import boto3
def lambda_handler(event, context):
client = boto3.client('cognito-idp')
username = event.get("username")
userpoolId = event.get("userpoolId")
mfa = event.get("mfa")
client.admin_set_user_mfa_preference(
SMSMfaSettings={
'Enabled':mfa,
'PreferredMfa':mfa
},
SoftwareTokenMfaSettings={
'Enabled': False,
'PreferredMfa':False
},
Username=username,
UserPoolId=userpoolId
)
Here is the how JavaScript lambda can invoke the Python Lambda function,
const aws = require('aws-sdk')
exports.handler = async function(event, context) {
const lambda = new aws.Lambda({
region: 'us-west-2'
});
let mfaResponse = await lambda.invoke({
FunctionName: 'setMFA',
Payload: JSON.stringify(
userPoolId : "userPoolId",
username : "Username",
mfa : true
)
}
}