I'm writing a Blazor server-side app with Windows Authentication enabled in the project.
I'm unable to use Role/Policy based authentication (I don't have access to change users roles/policies) and instead will be grabbing a set of usernames from a SQL database to check against the current user as to what parts of the NavMenu they can access.
I'm struggling to get the windows username available to all components and accessible from within the @code section though.
I've seen in the App.razor they use CascadingAuthenticationState component and an AuthoriseView component
I know you can use @context.User.Identity.Name to display the username but I'm not sure how to access the @context from within a @code section to get the username.
I've also tried this code and in the app which displays the username successfully:
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
private string _authMessage;
private async Task LogUsername()
{
var authState = await authenticationStateTask;
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
_authMessage = $"{user.Identity.Name} is authenticated.";
}
else
{
_authMessage = "The user is NOT authenticated.";
}
}
But I don't like the idea of repeating something like this async code in every component.
My simple idea was to create an "AuthorisationService" class and register it as a singleton. This would get the set of usernames from SQL and the current user at the outset when the page is first loaded and the logic of checking can live in there.
I'd inject it into every component and for the NavMenu I can have if-statements as to who can access what making them visible or not .
If anyone can shed some light on how to get the windows username in this way (or a better way if one exists as I'm just learning and completely new to Blazor) that would be great!
Many Thanks
Nick
AuthInfotype class, set the properties on that, and then set that as aCascadingValue. Then you don't need to do anyInvokeAsyncstuff in consuming components. - Peter Morris