Reputation: 11501
I have some code that should run in a console application and does some initialization for the users. The code is in dot net core 3.1 and I need to get the current user's email out from the environment to do the task. How do I do it?
From the Environment I see that I can access the UserName, but that is basically the person's Name.
Environment.UserName
Any suggestions?
The assumption is that the users are logged in to Windows/Mac with their Azure Active Directory user and therefore have all necessary data which is email in here.
The az login
is the first action before running the app. Can we take anything out of that token?
Upvotes: 0
Views: 566
Reputation: 155428
Preface: This answer assumes familiarity with OIDC, the structure of a JWT, and that you know the differences and responsibilities of access_token
and id_token
.
This answer is based on this blog post: https://mikhail.io/2019/07/how-azure-cli-manages-access-tokens/
When a user runs az login
and the OIDC authentication flow is successful, then the Azure CLI (az
) will save the current credential state to disk at ~/.azure/
. As of March 2020, the az
executable does not attempt to encrypt or otherwise protect its cached OIDC tokens from other user processes (for better or for worse) - in this case it's a good thing - provided you don't mind malware easily nabbing your credentials.
The user's e-mail address (at least, their e-mail address associated with their AzureAD account) will be inside their OIDC identity token JWT (id_token
) - this doesn't seem to be cached by az login
so you'll need to use an OIDC client to use the plaintext access_token
extracted from the ~/.azure/accessTokens.json
file to request the OIDC userinfo
(User Profile Resource) from AzureAD's OIDC service (assuming the access_token
grants you access to the User Profile Resource in the first place).
But assuming you do have access to the User Profile Resource, the user's e-mail address will be in the email
claim property.
Upvotes: 1
Reputation: 155428
You cannot get the current operating system's user's e-mail because it isn't defined.
I think you're referring to UPN-style usernames as seen in Windows Active Directory domains which are of the form {userName}@{fqdn}
, e.g. [email protected]
(where corp.bob.com
is the fully-qualified Active Directory domain name). A UPN is often, but not always, a user's e-mail address because of Microsoft Exchange Server's default configuration.
...but UPNs don't exist on platforms that don't use Active Directory, such as embedded systems and most Linux installations. You'd have to use the LDAP library in System.EnterpriseServices
to look it up (perhaps using ADSI).
Upvotes: 0