Get user E-mail or username in C# and Azure AD

Eskil Lundgren 1 Reputation point
2021-11-02T18:06:09.76+00:00

Hello!

So, what I want to do is get a hold username or e-mail to identify users. All users are external users invited to our Azure AD.
The below code return the app name:

@using Microsoft.Identity.Web
@using Microsoft.Extensions.Options
@using System.Security.Principal;
@using System.DirectoryServices;
@using System.Web;

@StrUserName

@code {
    private string StrUserName { get; set; 
    protected override void OnInitialized() {
    StrUserName = Environment.UserName;   
    }
}

How can I get the username or e-mail?

Cheers!

/Eskil

Microsoft Security | Microsoft Entra | Microsoft Entra ID
{count} votes

4 answers

Sort by: Most helpful
  1. James Hamil 27,221 Reputation points Microsoft Employee Moderator
    2021-11-03T23:14:33.88+00:00

    Hi @Eskil Lundgren , if I understand your task correctly, have you looked into bulk downloading? https://learn.microsoft.com/en-us/azure/active-directory/enterprise-users/users-bulk-download

    You can export all user data from the portal. Please let me know if this works for you!

    If this answer helped you please mark it as "Verified" so other users may reference it.

    Thank you,
    James

    0 comments No comments

  2. Eskil Lundgren 1 Reputation point
    2021-11-04T08:36:14.85+00:00

    Hello James!

    Sorry if I was unclear in my original post.

    What I want to do is get the username in code, the code I posted is contained in an azure Blazor server app.

    0 comments No comments

  3. James Hamil 27,221 Reputation points Microsoft Employee Moderator
    2021-11-05T21:47:44.09+00:00

    Hi @Eskil Lundgren , I think I understand now! I found this article that goes into detail on user authentication: https://devblogs.microsoft.com/microsoft365dev/how-to-build-a-blazor-web-app-with-azure-active-directory-authentication-and-microsoft-graph/

    After the user is authenticated you can use this to pull their information and display it how you please:

    <AuthorizeView>  
        <Authorized>  
            Hello, @context.User.Identity.Name!  
            <a href="MicrosoftIdentity/Account/SignOut">Log out</a>  
        </Authorized>  
        <NotAuthorized>  
            <a href="MicrosoftIdentity/Account/SignIn">Log in</a>  
        </NotAuthorized>  
    </AuthorizeView>  
    

    I hope this helps. Please let me know if you have any questions.

    Best,
    James

    0 comments No comments

  4. Chapman, Jeremy 0 Reputation points
    2023-02-21T22:31:31.5633333+00:00

    How would one get the current users display name and email address? @context.User does not have this information.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.