Skip to content

Windows authentication sample for Blazor Web #460

@markat1

Description

@markat1

I understand that windows authentication is not something that's recommended, BUT this is for projects running local protected environment, where I have access to active directory.

I'm struggling to find best practice when it come to having both a server and client side. So a sample is deperately needed.

In .net 6 I managed windows authentication with the following, which made me able to run username and hasrole without any issues across the whole application (after great tip from @javiercn):

//_Host.cshtml
@page "/"
@namespace TestExample.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@{
    Layout = "_Layout";

    var userconfig = new InitialApplicationState
    {
        UserName = HttpContext?.User?.Identity?.Name,
        HasRole = HttpContext?.User?.IsInRole("test")
    };
}

<component type="typeof(App)" param-InitialState="userconfig" render-mode="Server" />

But in .net 9 I don't have _host anymore and I also need to manage with the client part. (followed the document in here)

So I tried with cascading authentication state, but I'm not sure if that's best practice.
Basically added builder.Services.AddCascadingAuthenticationState(), which then made me able
to cascade authentication state down to client, so I was able to use

Hello, @(!string.IsNullOrEmpty(context.User.Identity?.Name) ? "Mark" : "Not authenticated")

Though I was unable to receive user claims even after adding the following on server side (program.cs):

        builder.Services.AddRazorComponents()
                        .AddInteractiveServerComponents()
                        .AddInteractiveWebAssemblyComponents()
                        .AddAuthenticationStateSerialization(options => options.SerializeAllClaims = true);

Strange enough client is able to understand specific roles if I use @Attribute [Authorize(Roles = "myrole")], but I'm unable to receive the list of claims if I try manually fetching claims via @context.user.Claims

 <AuthorizeView>
    <p>Hello, @context.User.Identity?.Name</p>
    <p>@context.User.Identity.IsAuthenticated</p>
    <p>is in role test1?: @context.User.IsInRole("test1")</p>   // returns false even though it's true)
    <p>is in role test2?: @context.User.IsInRole("test2")</p> // returns false even though it's true)

</AuthorizeView> 

any clue what's happening here Luke ? @guardrex

Metadata

Metadata

Assignees

Labels

DocumentationImprovements or additions to documentation

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions