How to retrieve the user claims in a Blazor server side app after the user has logged in?

Viewed 955

I have a Blazor server application and a AD B2C authentication. I have configured the Azure and the application is working fine. I can also see the claims with the following code.

<AuthorizeView>
    <Authorized>
        <table style="border: 1px solid black;">
            <tr style="border: 1px solid black; padding: 2px;">
                <th style="border: 1px solid black; padding: 2px;">Claim Type</th>
                <th style="border: 1px solid black; padding: 2px;">Value</th>
            </tr>

            @foreach (var item in context.User.Claims)
            {
                <tr style="border: 1px solid black; padding: 2px;">
                    <td style="border: 1px solid black; padding: 2px;">@item.Type</td>
                    <td style="border: 1px solid black; padding: 2px;">@item.Value</td>
                </tr>
            }
        </table>
    </Authorized>
</AuthorizeView>

I want to access the user claims in a C# class (not in a razor file) and save in a database. How can I achieve that? Are the claims stored in a global object like HttpContext from where I can retrieve those?

1 Answers

You can make use of AuthenticationStateProvider and from GetAuthenticationStateAsync method you can get user claims. A sample would be something like this

public class Temp
{
    private readonly AuthenticationStateProvider _auth;

    public Temp(AuthenticationStateProvider auth)
    {
        _auth = auth;
    }

    public async Task GetClaims()
    {
        var authState = await _auth.GetAuthenticationStateAsync();
        var userClaims = authState.User.Claims;
    }
}
Related