I have a single component in a Blazor / .NET 8 project that needs to be accessible by only specific domain users. Prior to .NET Core, when an application was published to IIS, you could do this by using the <location path="...">
element along with appropriate <allow/>
and <deny/>
elements within the web.config
file.
However, web.config
can no longer be used to accomplish this task given the nature of Blazors routing behavior and attempts to do so using the web.config
results in 404 errors for any domain user trying to access the component to be restricted.
I have tried to use the [Authorize]
attribute on the target Razor page and inside of the OnInitialized
lifecycle method for it, the line
string? username = this.HttpContextAccessor.HttpContext?.User?.Identity?.Name;
was added to retrieve the username, but here is the kicker...
The OnInitialized
method is called twice, presumably because I'm using @rendermode InteractiveServer
, and @rendermode @(new InteractiveServerRenderMode(prerender: false))
has no affect either.
The first time OnInitialized
is called, I can see my username on the identity property from the HttpContext
, but the second time the method is called in the rendering process, that value is NULL.
It's almost as if the anonymous aspect of the application is overriding the [Authorize]
aspect of the component. If I turn off anonymous authentication, then I will always have a name value on the identity, but if both anonymous and Windows authentication are turned on, when OnInitialized
is triggered the second time, the value is NULL.
My ultimate goal here is to get the Windows username, and cross check it with a list of usernames and if a match is found, the user can access the page, otherwise they can't.
Can someone explain what is happening here and how best to resolve it or provide a more appropriate implementation example to address this scenario?
Thanks.