Force role session name in AWS IAM I want to enforce users to use their IAM username as the role session name when assuming a role in AWS. I've tried the following condition in IAM policies:
{
  &quot;Effect&quot;: &quot;Allow&quot;,
  &quot;Principal&quot;: {
    &quot;AWS&quot;: &quot;arn:aws:iam::&lt;redacted&gt;:root&quot;
  },
  &quot;Action&quot;: &quot;sts:AssumeRole&quot;,
  &quot;Condition&quot;: {
    &quot;StringLike&quot;: {
      &quot;sts:RoleSessionName&quot;: &quot;${aws:username}&quot;
    }
  }
}

While this works fine when assuming a role as a user it does not work when assuming a role from a role with administrator privileges (Allow * on *). The only way to block this would be an explicit Deny when a role tries to assume a given role and does not have session name set up. Any ideas how to write a policy doing this? A simple Deny like below does not work because aws:username is not present when Assumed Role is the principal (see docs).
{
  &quot;Effect&quot;: &quot;Deny&quot;,
  &quot;Principal&quot;: {
    &quot;AWS&quot;: &quot;arn:aws:iam::&lt;redacted&gt;:root&quot;
  },
  &quot;Action&quot;: &quot;sts:AssumeRole&quot;,
  &quot;Condition&quot;: {
    &quot;StringNotLike&quot;: {
      &quot;sts:RoleSessionName&quot;: &quot;${aws:username}&quot;
    }
  }
}
I have not tried it but I think if you change your deny to a list of elements it will work.
{
  &quot;Effect&quot;: &quot;Deny&quot;,
  &quot;Principal&quot;: {
    &quot;AWS&quot;: &quot;arn:aws:iam::&lt;redacted&gt;:root&quot;
  },
  &quot;Action&quot;: &quot;sts:AssumeRole&quot;,
  &quot;Condition&quot;: {
    &quot;StringNotLike&quot;: {
      &quot;sts:RoleSessionName&quot;: [
        &quot;${aws:username}&quot;,
        &quot;AnotherAllowedName&quot;
      ]
    }
  }
}

This will allow an IAM user to assume the role if they use their username as the session name and it will also allow other Principals to assume the role if they use &quot;AnotherAllowedName&quot; as the session name but all other session names would be declined. I found this AWS blog post helpful when researching this answer