biostat
biostat

Reputation: 565

How to enable/fix windows authentication in Blazor Server-Side App?

When we created our server-side blazor app (ASP.NET Core Web App) initially we did not enable authentication. We would like to enable windows authentication now.

I created a test web app with windows authentication and tried adding missing bits into our existing web app. Below are the changes that I made:

  1. Modified app.razor to include cascadingauthenticationstate
<Router AppAssembly="@typeof(Program).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <CascadingAuthenticationState>
                <LayoutView Layout="@typeof(MainLayout)">
                    <p>Sorry, there's nothing at this address.</p>
                </LayoutView>
            </CascadingAuthenticationState>
        </NotFound>
    </Router>
  1. Added missing imports in _imports.razor
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
  1. Tried fetching current windows identity using below code block in a razor component:
@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    private async Task LogUsername()
    {
        var authState = await authenticationStateTask;
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            Console.WriteLine($"{user.Identity.Name} is authenticated.");
        }
        else
        {
            Console.WriteLine("The user is NOT authenticated.");
        }
    }
}

When I run the web app locally in Visual Studio 2019 preview, I am always ending up with an empty identity name. And, IsAuthenticated is always false. However, if I run the test web app locally, it gets the correct identity name.

Does anyone know what I am missing in my existing web app?

Thanks!

Upvotes: 10

Views: 11713

Answers (3)

b166er
b166er

Reputation: 209

I have a Blazor Server project that has two possible debug start profiles Visual Studio Debug options

The web project itself XX.SD starts in the browser but the launch profile does not have an option for Windows Authentication. The IIS Express lauch profile however does have this option in the Properties page.

Upvotes: 4

david magdy
david magdy

Reputation: 11

Just Enable windows Authentication button : Project=>properties => Debug => web server settings

Upvotes: 1

biostat
biostat

Reputation: 565

Apparently, I missed checking the box for windows authentication under Project Properties > Debug tab.

Upvotes: 10

Related Questions