Created
September 9, 2024 18:29
-
-
Save KaiserWerk/7bc0eacbaf621a3897c3b14aa33b287e to your computer and use it in GitHub Desktop.
Get User Claims (and ID) in Balzor page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@page "/" | |
@using System.Security.Claims | |
@inject AuthenticationStateProvider AuthenticationStateProvider | |
<PageTitle>Home</PageTitle> | |
<h1>Hello, world!</h1> | |
Welcome to your new app. | |
<h3>ClaimsPrincipal Data</h3> | |
<p>@_authMessage</p> | |
@if (_claims.Count() > 0) | |
{ | |
<table class="table"> | |
@foreach (var claim in _claims) | |
{ | |
<tr> | |
<td>@claim.Type</td> | |
<td>@claim.Value</td> | |
</tr> | |
} | |
</table> | |
} | |
<p>@_userId</p> | |
@code { | |
private string _authMessage; | |
private string _userId; | |
private IEnumerable<Claim> _claims = Enumerable.Empty<Claim>(); | |
protected override async Task OnParametersSetAsync() | |
{ | |
await GetClaimsPrincipalData(); | |
await base.OnParametersSetAsync(); | |
} | |
private async Task GetClaimsPrincipalData() | |
{ | |
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); | |
var user = authState.User; | |
if (user.Identity.IsAuthenticated) | |
{ | |
_authMessage = $"{user.Identity.Name} is authenticated."; | |
_claims = user.Claims; | |
_userId = user.Claims.Where(e => e.Type.Contains("identity/claims/nameidentifier")).First().Value; | |
} | |
else | |
{ | |
_authMessage = "The user is NOT authenticated."; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment