How to set/get user name instead of email using identity?

Cenk 1,036 Reputation points
2023-02-12T12:28:02.2966667+00:00

Hi friends,

In my Blazor Server application, I am using scaffolded Identity pages. Out of the box, the userid (e-mail) is shown by the LoginDisplay.razor component.

 <a  class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity?.Name!</a>

Here is how I manage users.

@page "/administration"

@using Microsoft.AspNetCore.Authorization;
@using Microsoft.AspNetCore.Identity;
@using System.Security.Claims
@inject UserManager<IdentityUser> _UserManager
@inject RoleManager<IdentityRole> _RoleManager
@inject AuthenticationStateProvider AuthenticationStateProvider

<h1>User Management</h1>
<br/>
<AuthorizeView>

    <Authorized>

        @if (context.User.IsInRole(ADMINISTRATION_ROLE))

        {
            <table class="table">

                <thead>

                    <tr>

                        <th>Id</th>

                        <th>User Name</th>

                        <th>Email</th>

                    </tr>

                </thead>

                <tbody>

                    @foreach (var user in ColUsers)

                    {
                        <tr>

                            <td>@user.Id.Substring(0, 5) ...</td>

                            <td>@user.UserName</td>

                            <td>@user.Email</td>

                            <td>

                                <!-- Edit the current forecast -->

                                <button class="btn btn-primary"
                                @onclick="() => EditUser(user)">

                                    Edit

                                </button>

                            </td>

                        </tr>
                    }

                </tbody>

            </table>
            @if (ShowPopup)

            {
                <!-- This is the popup to create or edit a user -->

                <div class="modal" tabindex="-1" style="display: block" role="dialog">

                    <div class="modal-dialog">

                        <div class="modal-content">

                            <div class="modal-header">

                                <h3 class="modal-title">User Details</h3>

                                <!-- Button to close the popup -->

                                <button type="button" class="close"
                                @onclick="ClosePopup">

                                    <span aria-hidden="true">X</span>

                                </button>

                            </div>

                            <!-- Edit form for the current user -->

                            <div class="modal-body">

                                <!-- Only show Id if not a new user -->
                                @if (objUser.Id != "")

                                {
                                    <p>@objUser.Id</p>
                                }

                                <!-- Only allow edit if a new user -->
                                @if (objUser.Id != "")

                                {
                                    <p>@objUser.UserName</p>
                                }

                                else

                                {
                                    <input class="form-control" type="text"
                               placeholder="UserName"
                               @bind="objUser.UserName" style="margin-bottom: 10px"/>
                                }

                                <input class="form-control" type="text"
                               placeholder="Email"
                               @bind="objUser.Email" style="margin-bottom: 10px"/>

                                <input class="form-control" type="password"
                               placeholder="Password"
                               @bind="objUser.PasswordHash" style="margin-bottom: 10px"/>

                                <select class="form-control"
                                @bind="@CurrentUserRole" style="margin-bottom: 10px">

                                    @foreach (var option in Options)

                                    {
                                        <option value="@option">

                                            @option

                                        </option>
                                    }

                                </select>

                                <br /><br />

                                <!-- Button to save the user -->

                                <button class="btn btn-primary"
                                @onclick="SaveUser" style="margin-right: 10px">

                                    Save

                                </button>

                                <!-- Only show delete button if not a new record -->
                                @if (objUser.Id != "")

                                {
                                    <!-- Button to delete the forecast -->

                                    <button class="btn btn-danger"
                                @onclick="DeleteUser">

                                        Delete

                                    </button>
                                }

                                <br />

                                <span style="color: red">@strError</span>

                            </div>

                        </div>

                    </div>

                </div>
            }

            <button class="btn btn-success" @onclick="AddNewUser">Add User</button>
        }

        else

        {
            <p>You're not signed in as a user in @ADMINISTRATION_ROLE.</p>
        }

    </Authorized>

    <NotAuthorized>

        <p>Sorry,You're not loggged in!</p>

    </NotAuthorized>

</AuthorizeView>


@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    readonly string ADMINISTRATION_ROLE = "Administrators";

    ClaimsPrincipal CurrentUser;

    // Property used to add or edit the currently selected user
    IdentityUser objUser = new();

    // Tracks the selected role for the currently selected user
    string CurrentUserRole { get; set; } = "Users";

    // Collection to display the existing users
    List<IdentityUser> ColUsers = new();

    // Options to display in the roles dropdown when editing a user
    readonly List<string> Options = new() { "Users", "Administrators" };

    // To hold any possible errors
    string strError = "";

    // To enable showing the Popup
    bool ShowPopup;

    void AddNewUser()
    {
        // Make new user
        objUser = new IdentityUser
        {
            PasswordHash = "*****",
            // Set Id to blank so we know it is a new record
            Id = ""
        };

        // Open the Popup
        ShowPopup = true;
    }


    async Task SaveUser()
    {
        try
        {
            // Is this an existing user?
            if (objUser.Id != "")
            {

                // Get the user
                var user = await _UserManager.FindByIdAsync(objUser.Id);

                // Update Email
                user.Email = objUser.Email;

                // Update the user
                await _UserManager.UpdateAsync(user);

                // Only update password if the current value
                // is not the default value
                if (objUser.PasswordHash != "*****")
                {

                    var resetToken = 
                        await _UserManager.GeneratePasswordResetTokenAsync(user);

                    var passworduser = 
                        await _UserManager.ResetPasswordAsync(
                            user, 
                            resetToken, 
                            objUser.PasswordHash);

                    if (!passworduser.Succeeded)
                    {
                        if (passworduser.Errors.FirstOrDefault() != null)
                        {

                            strError = 
                                passworduser
                                .Errors
                                .FirstOrDefault()
                                .Description;
                        }
                        else
                        {
                            strError = "Password error";
                        }

                        // Keep the popup opened
                        return;

                    }
                }

                // Handle Roles
                // Is user in administrator role?
                var UserResult = 
                    await _UserManager
                    .IsInRoleAsync(user, ADMINISTRATION_ROLE);

                // Is Administrator role selected 
                // but user is not an Administrator?
                if ((CurrentUserRole == ADMINISTRATION_ROLE) &(!UserResult))
                {
                    // Put admin in Administrator role
                    await _UserManager
                        .AddToRoleAsync(user, ADMINISTRATION_ROLE);

                }
                else
                {
                    // Is Administrator role not selected 
                    // but user is an Administrator?
                    if ((CurrentUserRole != ADMINISTRATION_ROLE) & (UserResult))
                    {
                        // Remove user from Administrator role
                        await _UserManager
                            .RemoveFromRoleAsync(user, ADMINISTRATION_ROLE);
                    }
                }
            }
            else
            {
                // Insert new user
                var NewUser =
                    new IdentityUser
                    {
                        UserName = objUser.UserName,
                        Email = objUser.Email
                    };

                var CreateResult =
                    await _UserManager
                    .CreateAsync(NewUser, objUser.PasswordHash);
                if (!CreateResult.Succeeded)
                {
                    if (CreateResult.Errors.FirstOrDefault() != null)
                    {
                        strError =
                            CreateResult
                            .Errors
                            .FirstOrDefault()
                            .Description;
                    }
                    else
                    {
                        strError = "Create error";
                    }

                    // Keep the popup opened
                    return;
                }
                else
                {
                    // Handle Roles
                    if (CurrentUserRole == ADMINISTRATION_ROLE)
                    {
                        // Put admin in Administrator role
                        await _UserManager
                            .AddToRoleAsync(NewUser, ADMINISTRATION_ROLE);
                    }

                }

            }

            // Close the Popup
            ShowPopup = false;

            // Refresh Users
            GetUsers();

        }
        catch (Exception ex)
        {
            strError = ex.GetBaseException().Message;
        }

    }


    async Task DeleteUser()
    {
        // Close the Popup
        ShowPopup = false;

        // Get the user
        var user = await _UserManager.FindByIdAsync(objUser.Id);

        if (user != null)
        {
            // Delete the user
            await _UserManager.DeleteAsync(user);
        }

        // Refresh Users
        GetUsers();
    }

    async Task EditUser(IdentityUser _IdentityUser)
    {
        // Set the selected user
        // as the current user
        objUser = _IdentityUser;

        // Get the user
        var user = await _UserManager.FindByIdAsync(objUser.Id);
        if (user != null)
        {
        // Is user in administrator role?
        var UserResult =
            await _UserManager
            .IsInRoleAsync(user, ADMINISTRATION_ROLE);

            CurrentUserRole = UserResult ? ADMINISTRATION_ROLE : "Users";
        }

        // Open the Popup
        ShowPopup = true;

    }

    void ClosePopup()
    {
        // Close the Popup
        ShowPopup = false;
    }

    protected override async Task OnInitializedAsync()
    {
        // ensure there is a ADMINISTRATION_ROLE
        var RoleResult = await _RoleManager.FindByNameAsync(ADMINISTRATION_ROLE);

        if (RoleResult == null)
        {
            // Create ADMINISTRATION_ROLE Role
            await _RoleManager.CreateAsync(new IdentityRole(ADMINISTRATION_ROLE));
        }

        // Ensure a user named ******@BlazorHelpWebsite.com is an Administrator
        var user = await _UserManager.FindByNameAsync("******@gmail.com");

        if (user != null)
        {
            // Is ******@BlazorHelpWebsite.com in administrator role?
            var UserResult = await _UserManager.IsInRoleAsync(user, ADMINISTRATION_ROLE);

            if (!UserResult)
            {
                // Put admin in Administrator role
                await _UserManager.AddToRoleAsync(user, ADMINISTRATION_ROLE);
            }
        }

        // Get the current logged in user
        CurrentUser = (await authenticationStateTask).User;

        // Get the users
        GetUsers();
    }

    private void GetUsers()
    {
        // clear any error messages
        strError = "";

        // Collection to hold users
        ColUsers = new List<IdentityUser>();

        // get users from _UserManager
        var user = _UserManager.Users.Select(x => new IdentityUser
            {
                Id = x.Id,
                UserName = x.UserName,
                Email = x.Email,
                PasswordHash = "*****"
            });

        foreach (var item in user)
        {
            ColUsers.Add(item);
        }
    }


}

I wonder if I can display the name instead of the e-mail?

Thank you.

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | Blazor
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2023-02-12T12:37:02.85+00:00

    The template uses the email address as the username and the email address! Just add a username input and set the the username as the username rather than the email address.

    0 comments No comments

  2. Michael Washington 921 Reputation points MVP
    2023-02-12T13:54:43.4533333+00:00

    See this for how to scaffold the Identity pages and customize the Register and Login screens: Customizing The Blazor Login Process With External Authentication Providers

    image

    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.