Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 909
biostat Avatar asked Jan 26 '23 20:01

biostat


1 Answers

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

like image 118
biostat Avatar answered May 12 '23 04:05

biostat