I have a Blazor Server app registered in Microsoft Entra ID and I want to get the logged in user data and some other users data, too. I registered this app in this way:
- Add permissions to another API : API URL: https://graph.microsoft.com/User.Read.All
- Sopes defined by the API: User.Read.All
How can I get these user information (name, uid, email address, etc.) from Azure, please? This solution works for me, but I would like to use it as a service per request in Program.cs:
[CascadingParameter]
private Task<AuthenticationState>? authenticationState { get; set; }
protected override async Task OnInitializedAsync()
{
if (authenticationState is not null)
{
var authState = await authenticationState;
var user = authState?.User;
if (user?.Identity is not null && user.Identity.IsAuthenticated)
{
authMessage = $"{user.Identity.Name} is authenticated.";
var claims = user.Claims;
//These are just examples
var uid = claims.Where(x => x.Type.Equals("uid")).FirstOrDefault().Value;
var name = claims.Where(x => x.Type.Equals("name")).FirstOrDefault().Value;
}
}
}
UPDATE I tried this but it gives me an error:
无效行动 例外: Cannot提供BlazorServerAppAzureAD.Pages类财产使用者的价值。 指数。 没有关于BlazorServerAppAzureAD的注册服务。 数据。
builder.Services.AddScoped<IUser, User>(st =>
{
var authState = st.GetService<AuthenticationState>();
var user = authState?.User;
if (user?.Identity is not null && user.Identity.IsAuthenticated)
{
var claims = user.Claims;
var uid = claims.Where(x => x.Type.Equals("uid")).FirstOrDefault().Value;
var name = claims.Where(x => x.Type.Equals("name")).FirstOrDefault().Value;
var email = claims.Where(x => x.Type.Equals("preferred_username")).FirstOrDefault().Value;
return new User { Id = new Guid(uid), Name = name, UserName = user.Identity.Name, Email = email };
}
return null;
});