Forum Discussion

KevonH's avatar
KevonH
Copper Contributor
Jan 03, 2024

Blazor InteractiveAuto + Authentication

On pages which have @rendermode InteractiveAuto, the AuthenticationStateProvider which comes with the template does not seem to handle the transfer from server rendering to client rendering.

 

Steps to recreate:

 

Create a standard Blazor App with mode = InteractiveAuto on a global scope.  
Following the instructions here: https://learn.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-8.0, create a ClaimsPrincipalData.razor, but alter it so that it uses @rendermode Interactive Auto like this:

 

PAGE "/claims-principle-data"
@using System.Security.Claims
@inject AuthenticationStateProvider AuthenticationStateProvider
@rendermode InteractiveAuto

<h1>ClaimsPrincipal Data</h1>

<p>@authMessage</p>

@if (claims.Count() > 0)
{

    <ul>
        @foreach (var claim in claims)
        {
            <li>@claim.Type: @claim.Value</li>
        }
    </ul>
}

<p>@surname</p>

@code {
    private string? authMessage;
    private string? surname;
    private IEnumerable<Claim> claims = Enumerable.Empty<Claim>();

    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthenticationStateProvider
            .GetAuthenticationStateAsync();
        var user = authState.User;

        if (user.Identity is not null && user.Identity.IsAuthenticated)
        {
            authMessage = $"{user.Identity.Name} is authenticated.";
            claims = user.Claims;
            surname = user.FindFirst(c => c.Type == ClaimTypes.Surname)?.Value;
        }
        else
        {
            authMessage = "The user is NOT authenticated.";
        }
    }
}

 

 

Run the program and initialize the database using the migrations, then register a user.  

Put a breakpoint at line 34.

The first time it runs (server side rendering), you'll see that there are 4 claims.

The second time it runs (client wasm side rendering), there will only be 3 claims.

 

In my implementation and testing, I had also added a role to my test user.

First execution (Server Side):

Second execution (wasm):

 

So, the question is.... how does one persist claims when using InteractiveAuto so that the WASM execution ALSO has access to all of the claims?

No RepliesBe the first to reply

Resources