Ruby AWS SDK - Using Aws::AssumeRoleCredentials without mfa token

Viewed 498

Im getting to grips with AWS authentication and seem to have hit a blank with using Aws::AssumeRoleCredentials object.

Hopefully I'm just misunderstanding if I should even be using it.

I have a successful method of assuming the role when using an mfa token:

# Assume the role referenced in the profile
def assume_role(mfa_token_code = nil)
  sts_client = Aws::STS::Client.new(credentials: @user_credentials, region: @user_profile.region)

  @role_credentials = sts_client.assume_role(
     {
       role_arn: @user_profile.role_arn, # required
       role_session_name: @session_name, # required
       duration_seconds: @duration_seconds,
       serial_number: @user_profile.mfa_serial,
       token_code: mfa_token_code.to_s
    }
  )
end

This works fine but requires the mfa token.

I think its is possible to then authenticate again if the session hasn't timed out, without needing to prompt the user for another mfa token, but I'm struggling to find a way to do it.

I'm tinkering around with the AssumeRoleCredentials object in the hope that it is the correct object for this:

def authenticate_as_application_user

  begin
    @role_credentials = Aws::AssumeRoleCredentials.new(
      # client: Aws::STS::Client.new(credentials: @user_credentials, region: @user_profile.region),
      duration_seconds: @duration_seconds,
      role_arn: @user_profile.role_arn,
      role_session_name: 'session-name-xxxxxxxxx'
    )
  rescue
    puts 'Enter MFA code: '
    mfa_token_code = gets.chomp
    unless mfa_token_code.nil?
      assume_role(mfa_token_code)
    else
      puts('No code supplied, aborting')
    end
  end
end

No matter what I try this code fails to assume the role with an error:

Access denied

I know from other python tools that I'm using that if I authenticate with an mfa token, and then re run the tool, I'm not prompted again until the original session timeout expires.

What am I doing wrong?

Thanks

0 Answers
Related