To use multi-factor authentication with the AWS CLI, you exchange your long-lived IAM user access key plus a current MFA code for temporary credentials, then run your commands with those. The newer aws configure mfa-login command does the exchange for you. If you can, skip the manual route and sign in through IAM Identity Center, which handles MFA in the browser, including passkeys and security keys. This guide covers both paths, the policy that makes MFA mandatory, and the mistakes that quietly turn enforcement off.
Table of Contents
ToggleTL;DR
- IAM users get MFA in the CLI by trading an access key and an MFA code for temporary credentials.
aws configure mfa-loginautomates this and writes the result to a profile. - Session credentials last 12 hours by default and can be set from 15 minutes to 36 hours, according to AWS re:Post.
- Hardware security keys and passkeys do not work with the manual token flow. Use IAM Identity Center and
aws sso loginfor those. - To force MFA, deny actions with
BoolIfExistsonaws:MultiFactorAuthPresent. A plainBoolcheck fails silently. - Whatever route you take, store the underlying secrets in a proper password manager, not in plain text files.
Why the CLI needs its own MFA step
Signing in to the AWS console with MFA protects the console. It does nothing for an access key sitting in ~/.aws/credentials. Anyone who copies that file can call the API with no second factor at all.
The fix is to make the long-lived key useless on its own. You require that API calls come from a session that was created with an MFA code. The key becomes a way to ask for a session, not a way to do work.
There are two models, and which one you use decides everything else in this guide:
| IAM user + MFA token | IAM Identity Center | |
|---|---|---|
| Credentials on disk | Long-lived access key plus temporary session | Short-lived, cached after browser login |
| MFA entry | Type a code on each session refresh | Browser prompt at the portal |
| Security keys and passkeys | Not supported in the CLI flow | Supported through the browser |
| Best for | Legacy accounts, break-glass users, small setups | Teams, MSPs, anything with more than a handful of people |
AWS itself recommends using temporary credentials and federation for human users rather than IAM users with access keys. The IAM user path still matters because plenty of accounts have it, and because you need to understand it to enforce MFA correctly.
Path 1: MFA with an IAM user
Step 1: Assign an MFA device
In the console, open the IAM user, go to the Security credentials tab and choose Manage next to the assigned MFA device. A virtual authenticator app is the usual choice. Note the device ARN, which looks like arn:aws:iam::123456789012:mfa/your-user. You need it for the CLI.
Step 2: Set up a base profile
Run aws configure with the user’s access key and secret key. This is your long-lived profile. Treat it as the dangerous one: by itself it should be able to do almost nothing once the enforcement policy below is in place.
Step 3: Get temporary credentials
The newer route is the CLI’s own helper. The mfa-login command gets temporary security credentials and places them in an AWS profile. It uses the long-lived access key and the MFA code from a virtual TOTP device. A typical call looks like this:

aws configure mfa-login --profile myprofile --update-profile mfaprofile
The older, manual route calls the Security Token Service directly:
aws sts get-session-token
--serial-number arn:aws:iam::123456789012:mfa/your-user
--token-code 123456
The response contains an access key ID, a secret access key and a session token. Put all three into a second profile, or export them as environment variables, and use that profile for real work. The steps are laid out in the AWS re:Post guide to MFA on the CLI.
Step 4: Know how long the session lasts
These credentials are valid for 12 hours by default. You can request anything from 15 minutes to 36 hours, per the same re:Post article. Shorter is safer for production access. Longer is tempting for scripts, but a script that needs 36 hours of unattended access probably should not be using a human’s MFA at all. Give it a role instead.
Step 5: Use the temporary profile
aws s3 ls --profile mfaprofile
When the session expires, calls start failing with an access denied or expired-token error. Run the login again. This is the friction people complain about, and it is why many teams eventually move to Identity Center.
Path 2: IAM Identity Center and aws sso login
IAM Identity Center (formerly AWS SSO) moves authentication out of the terminal. You configure a profile once with aws configure sso, then run aws sso login. The CLI opens your browser, you sign in and pass MFA there, and the CLI caches short-lived credentials.
This matters for three reasons.
- Security keys and passkeys work. The older GetSessionToken flow does not support FIDO/U2F/WebAuthn devices. AWS re:Post says users with those devices must use IAM Identity Center, which uses browser-based MFA.
- No long-lived key on the laptop. There is no access key to steal from a dotfile.
- Refresh is automatic. With the SSO token provider configuration, the CLI requests new credentials when the old ones expire, as long as your Identity Center session is still active. You only repeat the browser login when the portal session itself ends.
The basic flow:
aws configure sso
aws sso login --profile my-sso-profile
aws s3 ls --profile my-sso-profile
For a managed service provider handling dozens of client accounts, this is the practical choice. One login, many account profiles, MFA defined centrally. The AWS CLI documentation on configuring Identity Center walks through setup in detail.
Enforcing MFA instead of hoping for it
Setting up MFA does not require anyone to use it. If the base access key can still call ec2:TerminateInstances, a stolen key skips the whole exercise. Enforcement lives in IAM policy.
Use the right condition operator
The key to know is aws:MultiFactorAuthPresent. The trap is how it behaves in sessions without MFA: the key is simply absent. AWS’s own example for requiring MFA on specific EC2 operations therefore uses BoolIfExists rather than a plain Bool check. With Bool set to false, a request with no MFA key never matches, so the deny never fires and access goes through.
A minimal deny statement:
{
"Effect": "Deny",
"Action": ["ec2:StopInstances", "ec2:TerminateInstances"],
"Resource": "*",
"Condition": {
"BoolIfExists": {"aws:MultiFactorAuthPresent": "false"}
}
}
Read it as: deny these actions whenever MFA is absent or false. Test it with the base profile and confirm you get an explicit deny, then test with the MFA profile.
Require a fresh token for sensitive resources
MFA present is not the same as MFA recent. If you want a recent token for a production bucket, add aws:MultiFactorAuthAge. AWS’s S3 example denying production access without recent MFA uses a limit of 1800 seconds, or 30 minutes. Pair it with NumericGreaterThanIfExists so a missing age also triggers the deny.
The practical effect: someone who logged in with MFA at 9 a.m. cannot delete production objects at 3 p.m. without authenticating again.
GetSessionToken versus AssumeRole
The two calls treat MFA differently, and mixing them up is a common source of confusion. Credentials from GetSessionToken carry the MFA information, so resource-level policies can check it on every call. Credentials from AssumeRole do not carry that context the same way. AWS’s page on securing API access with MFA explains the difference. For roles, you enforce MFA in the role’s trust policy, at the moment of assumption.

In a cross-account setup that means the trust policy of the target role should require MFA, and the source account must be tidy too. If the source account does not restrict who can manage MFA devices, an attacker with enough permissions could register a device and produce an MFA claim that satisfies the target’s trust policy. Lock down iam:CreateVirtualMFADevice, iam:EnableMFADevice and friends for everyone but administrators.
Common errors and what they mean
- “AccessDenied” right after configuring MFA. You are probably still using the base profile. Check
aws sts get-caller-identity --profile mfaprofileand confirm the session profile is the one in use. - “MultiFactorAuthentication failed with invalid MFA one time pass code.” Usually clock drift on the device, a code that rolled over mid-command, or the wrong device ARN. Wait for the next code and retry.
- Commands worked this morning, fail now. The session expired. Re-run the login.
- Policy seems to do nothing. Check you used
BoolIfExists, notBool, as above. - Security key will not work in the terminal. Expected. Switch to Identity Center.
- A script breaks after you enforce MFA. Scripts should assume a role through a proper non-human mechanism instead of reusing a person’s code.
Our perspective: protect the key, not just the code
We build password and identity security tools, so we tend to look at this from the credential’s point of view. MFA on the CLI is a good control, but it protects the session. It does not protect the access key, the TOTP seed, or the recovery codes sitting in a notes file.
Three habits make the biggest difference in the teams we talk to:
- Keep the secret out of the shell history and out of dotfiles. The base access key and the MFA device ARN belong in an encrypted vault with access controls, not pasted into a wiki page.
- Prefer phishing-resistant factors. A six-digit code can be typed into a fake page. A passkey or security key tied to the real domain cannot. That is the logic behind passwordless MFA, and it is why Identity Center’s browser flow is a step up from typing codes into a terminal.
- Reduce how many humans hold long-lived keys. Every IAM user with an access key is a standing target. Fewer keys means fewer things to rotate, audit and lose. For organizations, this is the same lesson as the common enterprise password management mistakes: sprawl, shared secrets and missing offboarding do the damage, not exotic attacks.
AWS makes the same case in its documentation, steering teams toward temporary credentials and federation. Use MFA on the CLI where you must, and shrink the number of places you must.
— Mike
Where a password manager fits in an AWS workflow
Even with Identity Center, people still hold the console password for the root user, the credentials for the identity provider, the recovery codes for MFA devices and API keys for other services. Those need a home that is encrypted, shared on a need-to-know basis and recoverable when someone leaves.
LogMeOnce offers a password manager for individuals and teams. Personal plans: Professional is $2.50 per month, Ultimate is $3.25 per month and Family is $4.99 per month. For organizations, Teams is $4.00 per month per user and Business is $7.99 per month per user, with an Enterprise tier that has no published price. Managed service providers can see the full range of products on our resources page. If you are weighing the return for a team, the password manager ROI calculator gives you a starting figure.
A rollout checklist for admins
- Inventory IAM users with access keys. Delete the ones nobody uses.
- For humans, set up IAM Identity Center and move CLI access to
aws sso login. - For remaining IAM users, assign MFA devices and document the
mfa-loginorget-session-tokensteps. - Attach a deny policy with
BoolIfExistsso the base key cannot do real work without MFA. - Add
aws:MultiFactorAuthAgelimits to production resources. - Require MFA in the trust policy of any role that people assume, and restrict MFA device management in the source accounts.
- Move workloads and automation to roles with temporary credentials, not to someone’s personal key.
- Store recovery codes and root credentials in an encrypted vault with audited access.
- Test with the base profile, then the MFA profile, and record the expected deny.
FAQ
How do I use MFA with the AWS CLI?
Assign an MFA device to your IAM user, then run aws configure mfa-login or aws sts get-session-token with your device ARN and a current code. Use the temporary credentials it returns in a separate profile. If your organization uses IAM Identity Center, run aws sso login instead and complete MFA in the browser.
How long do the temporary credentials last?
The default is 12 hours. You can request anything between 15 minutes and 36 hours, according to AWS re:Post. Choose shorter lifetimes for production or administrative access.
Can I use a YubiKey or passkey with the AWS CLI?
Not through the GetSessionToken flow, which takes a typed code. Security keys and passkeys work through IAM Identity Center, where the browser handles the MFA step during aws sso login.
Why does my MFA policy not block anything?
Most often the condition uses Bool with aws:MultiFactorAuthPresent set to false. In sessions without MFA that key is missing, so the condition never matches. Switch to BoolIfExists, as in AWS’s EC2 example.
Is MFA enough to secure IAM user access keys?
No. MFA limits what a stolen key can do, but AWS still advises against long-lived IAM user keys for real data and recommends federation such as IAM Identity Center. Treat MFA on IAM users as a fallback, not the goal.
Sources
- Use the AWS CLI with MFA to authenticate | AWS re:Post
- mfa-login, AWS CLI Command Reference
- Security best practices in IAM
- login, AWS CLI Command Reference
- Configuring IAM Identity Center authentication with the AWS CLI (token provider)
- Configuring IAM Identity Center authentication with the AWS CLI
- Amazon EC2: Requires MFA for specific EC2 operations
- Amazon S3: production bucket denied without recent MFA
- Secure API access with MFA
- Authenticating using IAM user credentials for the AWS CLI
Recommended

Neha Kapoor is a versatile professional with expertise in content writing, SEO, and web development. With a BA and MA in Economics from Bangalore University, she brings a diverse skill set to the table. Currently, Neha excels as an Author and Content Writer at LogMeOnce, crafting engaging narratives and optimizing online content. Her dynamic approach to problem-solving and passion for innovation make her a valuable asset in any professional setting. Whether it’s writing captivating stories or tackling technical projects, Neha consistently makes impact with her multifaceted background and resourceful mindset.




Password Manager
Identity Theft Protection

Team / Business
Enterprise
MSP

