I have registered my Blazor Server application in the Microsoft Entra ID and I want to retrieve the authenticated user's data (name, email, ID, etc.). I have tried this code, but it is not a good solution:
[Inject]
GraphServiceClient GraphServiceClient { get; set; }
[Inject]
MicrosoftIdentityConsentAndConditionalAccessHandler ConsentHandler { get; set; }
private Guid _userId;
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
try {
var user = await GraphServiceClient.Me.Request().GetAsync();
_userId = new Guid(user.Id);
}
catch (Exception ex)
{
ConsentHandler.HandleException(ex);
}
}
My problem is that when I open the page, it reloads while querying user data, causing a white blank screen to flash up.
Solution
public interface IUserService
{
string Email { get; }
string FullName { get; }
Guid Id { get; }
Task InitializeAsync();
}
public class UserService : IUserService
{
private readonly AuthenticationStateProvider _authenticationStateProvider;
public string Email { get; private set; }
public string FullName { get; private set; }
public Guid Id { get; private set; }
public UserService(AuthenticationStateProvider authenticationStateProvider)
{
_authenticationStateProvider = authenticationStateProvider;
}
public async Task InitializeAsync()
{
var authenticationState = await _authenticationStateProvider.GetAuthenticationStateAsync();
var user = authenticationState.User;
Email = user.FindFirst("preferred_username")?.Value ?? "???";
FullName = user.FindFirst("name")?.Value ?? "???";
Id = new Guid(user.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value ?? "");
}
}
In Program.cs
builder.Services.AddScoped<IUserService, UserService>();
In use:
[Inject]
IUserService UserService { get; set; }
...
var userId = UserService.Id;