I have a Blazor Server app and have added the Login and Logout views. I’m trying to figure out where to access the claims when a user logs in. I am guessing the Login.cshtml page but there is no OnInitializedAsync method available since the Login view inherits from the PageModel class. I need to be able to get information from the claims and store them in localStorage so they are available to the rest of the application.
Am I going about this the right way? I initially put the following code on a Razor component (index.razor) and it worked fine but this isn’t the ideal place for it. Thoughts?
protected override async Task OnInitializedAsync()
{
var state = await AuthState.GetAuthenticationStateAsync();
Username = state.User.Identity.Name ?? string.Empty;
UserId = state.User.Claims
.Where(c => c.Type.Equals(@"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"))
.Select(c => c.Value)
.FirstOrDefault() ?? string.Empty;
Email = state.User.Claims
.Where(c => c.Type.Equals(@"https://myapi.com/email"))
.Select(c => c.Value)
.FirstOrDefault() ?? string.Empty;
var meta = state.User.Claims
.Where(c => c.Type.Equals(@"https://myapi.com/metadata"))
.Select(c => c.Value)
.FirstOrDefault();
Metadata = JsonConvert.DeserializeObject<Dictionary<string, string>>(meta);
await base.OnInitializedAsync();
}