I'm going to assume you're trying to do this in the client. I'm not completely sure if this is a secure enough way or the best approach, but hopefully someone will chime in if it isn't.
Keep in mind, this example isn't setup to Authorize by Roles, but it would need to be. I've kept it simpler in order to answer the specific question.
First, you'll need to add the Microsoft.AspNetCore.Identity.EntityFrameworkCore NuGet package to the Client project and the Shared project (or maybe a Models project if your architecture is setup that way).
Add a using directive to your Client _Imports file
@using YourProject.Shared
Copy the ApplicationUser.cs file from YourProject.Server > Models to YourProject.Shared. This model just inherits IdentityUser.
public class ApplicationUser : IdentityUser
{
}
If you wanted, you could add some validation attributes
public class ApplicationUser : IdentityUser
{
[Required]
[MaxLength(256)]
public override string UserName { get; set; }
}
Create a Controller in your Server project called MembersController
using System;
using System.Collections.Generic;
using System.Linq;
using YourProject.Server.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace YourProject.Server.Controllers
{
[Authorize]
[ApiController]
[Route("api/members")]
public class MembersController : ControllerBase
{
private UserManager<ApplicationUser> _userManager;
public MembersController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
[HttpGet]
public List<ApplicationUser> Get()
{
try
{
var users = _userManager.Users.OrderBy(p => p.UserName).ToList();
return users;
}
catch(Exception ex)
{
throw ex;
}
}
}
}
And add a component (i.e. Members.razor)
@page "/admin/membership"
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject HttpClient HttpClient
@attribute [Authorize]
<h3>Users</h3>
@if (_users == null)
{
<span>Loading Users...</span>
}
else
{
<ul>
@foreach (var user in _users)
{
<li>@user.UserName</li>
}
</ul>
}
<div class="@_exceptionClass">
@_error
</div>
@code {
private List<ApplicationUser> _users;
private string _exceptionClass = "d-none";
private string _error;
protected override async Task OnInitializedAsync()
{
try
{
_users = await HttpClient.GetFromJsonAsync<List<ApplicationUser>>("api/members");
}
catch (AccessTokenNotAvailableException exception)
{
exception.Redirect();
}
catch(Exception ex)
{
_exceptionClass = "d-block alert alert-danger";
_error = ex.Message;
}
}
}