Enabling Multi-Factor Authentication (MFA) for IAM Users
Introduction
In this lesson, we will learn how to enable multi-factor authentication (MFA) for IAM users in AWS. MFA adds an extra layer of security by requiring users to provide two or more authentication factors to verify their identity. We will explore practical examples using AWS CDK with Typescript to deploy infrastructure and enable MFA for IAM users.
Setting up the Environment
Before we begin, make sure you have the following prerequisites:
- An AWS account
- AWS CLI installed and configured
- Node.js and npm installed
- AWS CDK installed
Creating an IAM User with CDK
First, let’s create an IAM user using AWS CDK with Typescript. Create a new CDK project and install the necessary dependencies.
cdk init app --language typescript
npm install @aws-cdk/aws-iam
Next, define the IAM user in your CDK stack. Replace YOUR_USER_NAME
with the desired username.
import * as iam from '@aws-cdk/aws-iam';
const user = new iam.User(this, 'MyUser', {
userName: 'YOUR_USER_NAME',
});
Deploy the CDK stack to create the IAM user.
cdk deploy
Enabling MFA for IAM User
Now that we have created an IAM user, let’s enable MFA for the user. First, generate an MFA device for the user.
aws iam create-virtual-mfa-device --virtual-mfa-device-name MyMFADevice --outfile qrcode.png --bootstrap-method QRCodePNG
Scan the QR code using an authenticator app on your mobile device to link the MFA device.
Next, enable MFA for the IAM user.
aws iam enable-mfa-device --user-name YOUR_USER_NAME --serial-number arn:aws:iam::123456789012:mfa/MyMFADevice --authentication-code1 123456 --authentication-code2 654321
Replace 123456
and 654321
with the MFA codes generated by your authenticator app.
Testing MFA Authentication
To test MFA authentication, try logging in as the IAM user using the AWS CLI.
aws sts get-session-token --serial-number arn:aws:iam::123456789012:mfa/YOUR_USER_NAME --token-code 123456
Replace 123456
with the current MFA code from your authenticator app. If successful, you will receive temporary credentials.
Conclusion
In this lesson, we learned how to enable multi-factor authentication (MFA) for IAM users in AWS using practical examples with AWS CDK and Typescript. By following the steps outlined in this lesson, you can enhance the security of your AWS environment by requiring users to provide an additional authentication factor. Key learnings include creating an IAM user, generating an MFA device, enabling MFA for the user, and testing MFA authentication.