21

I'm using the Ruby SDK (V2), but I guess my question is more general than the specific implementation as I couldn't find an answer in any of the SDKs.

How do I get the username (and/or IAM user) that my session currently belongs to?

I let the SDK run its default behaviour for choosing credentials (ENV vars, then 'default' profile or other if specified and then machine role). Then I initialize my client and run commands. I'd like to know 'who is running the commands'. I expect to get the AWS username and if the chosen credentials were of an IAM user in it, then this username too.

Any ideas? The best I got so far was that after I build a Client object, I can query it's actual config and get Credentials. But that only gives me what credentials were chosen (i.e. SharedCredentials profile='default' vs. Credentials key=.. secret=..) and doesn't tell me who is the username behind it.

Many thanks!

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
Zach Moshe
  • 2,782
  • 4
  • 24
  • 40

2 Answers2

19

Be careful with your terminology -- interactions with the AWS APIs are all over HTTP, and are sessionless and stateless, so there's not really a concept of the currently "logged in" user, or a "session."

However, for a given set of credentials, you can fetch the attributes of the "current" user (the user whose credentials you're using) from Aws::IAM::CurrentUser.

http://docs.aws.amazon.com/sdkforruby/api/Aws/IAM/CurrentUser.html

Apologies for the lack of an example -- I am unfamiliar with Ruby in general -- but found this based on what I knew could be done with the direct query APIs and command line client with aws iam get-user. The available attributes are all the same: user_name, password_last_used, create_date, user_id, path, and arn... so I suspect this is what you're looking for.

From the Query API docs:

it defaults to the user making the request

Michael - sqlbot
  • 169,571
  • 25
  • 353
  • 427
  • 1
    Agree about the terminology. Indeed I meant the user whose credentials I'm using. Thanks about that, that gives me almost everything. I'll just add that if the user doesn't have the IAM:GetUser permission, we'll get an exception, but surprisingly enough, the exception message contains the ARN of the requesting user. Ugly, but works. Here is a thread that gives a code example to parse it: https://forums.aws.amazon.com/thread.jspa?threadID=108012 – Zach Moshe Dec 14 '15 at 22:04
  • Can someone give a similar link for java SDK? I tried to retrace in java doc but couldn't get it. – Sandip Kumar Jun 30 '20 at 12:33
8

STS (Security Token Service) provides an API for this:

GetCallerIdentity Returns details about the IAM identity whose credentials are used to call the API.

http://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.html

Michael Rush
  • 3,950
  • 3
  • 27
  • 23