How do I use IAM policy variables with federated users?

Last updated: 2020-08-19

When I use the GetFederationToken API to generate temporary credentials, the ${aws:userName} policy variable does not work.

Resolution

When using the GetFederationToken API, use the ${aws:userID} policy variable instead of the ${aws:userName} policy variable. This is because the variable ${aws:userName} isn't present if the principal is a federated user. For more information, see where you can use policy variables.

The following JSON IAM policy provides an example where the ${aws:userName} policy variable has been replaced with the ${aws:userID} policy variable:

{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Sid":"AllowListingOfUserFolder",
         "Action":[
            "s3:ListBucket"
         ],

         "Effect":"Allow",

         "Resource":[
            "arn:aws:s3:::TESTBUCKET"
         ],
         "Condition":{
            "StringLike":{
               "s3:prefix":[
                  "TESTBUCKET/${aws:userid}/*"
               ]
            }
         }
      },
      {
         "Sid":"AllowAllS3ActionsInUserFolder",
         "Action":[
            "s3:PutObject",
            "s3:GetObject",
            "s3:GetObjectVersion",
            "s3:DeleteObject"
         ],
         "Effect":"Allow",
         "Resource":[
            "arn:aws:s3:::TESTBUCKET/${aws:userid}/*"
         ]
      }
   ]
}

The value for the aws:userid variable should be "ACCOUNTNUMBER:caller-specified-name".

When calling the GetFederationToken API, the Name parameter value must follow the guidelines established in GetFederationToken. For example, if you specify the friendly name Bob, the correct format is "123456789102:Bob". This names your session and allows access to the Amazon Simple Storage Service (Amazon S3) bucket with a matching prefix.

Note: This example assumes that the caller-specified name (friendly name) portion of the aws:userid variable is unique. A unique friendly name prevents the scenario where another user with the same friendly name is not granted access to resources specified in the JSON policy. For more information, see Unique identifiers.