Getting Windows username in Blazor .Net 8 server app

Todd B 20 Reputation points
2024-07-31T20:31:48.31+00:00

Hi I'm new to Blazor and really to .Net Core also. I have the Visual Studio 2022 generated Blazor .Net 8 server app and need to access the username of the user logged into Windows from within the razor pages. I've perused the internet and tried multiple suggestions, none of which work for me. I always get one User.Identities object but no properties are set. Our sites don't require the user to login. They are allowed access to the sites if they exist in the site's users table.

Things I've tried:

  • Setting windowAuthentication = true and anonymousAuthentication = false in launchsettings.json
  • Injecting IHttpContextAccessor
  • Calling AuthenticationStateProvider.GetAuthenticationStateAsync()
  • Adding builder.Services.AddAuthentication() and app.UseAuthentication()

I'm at a loss at this point as to what is necessary. Again, the user won't be entering their username on the site. I need to grab it based on their Windows login. Anyone with a complete answer gets a gold star!

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,595 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jerry Fu - MSFT 816 Reputation points Microsoft Vendor
    2024-08-01T06:41:03.08+00:00

    Hi @Todd B,

    Similar to MVC/WebApi project, you could get the User information form HttpContext. For Blazor, using IHttpContextAccessor will let you access HttpContext in both SSR(Static Server rendering) and InterActiveServer(not full function, but could be used to get user info). You could try following steps:

    1. Create a Blazor Web App project. (no authentication, Server, global)
    2. Install Microsoft.AspNetCore.Authentication.Negotiate
    3. Create CustomAuthenticationStateProvider
             public class CustomAuthenticationStateProvider : AuthenticationStateProvider
             {
                 private readonly IHttpContextAccessor _httpContextAccessor;
                 public CustomAuthenticationStateProvider(IHttpContextAccessor httpContextAccessor)
                 {
                     this._httpContextAccessor = httpContextAccessor;
                 }
                 public override Task<AuthenticationState> GetAuthenticationStateAsync()
                 {        
                     var identity = _httpContextAccessor.HttpContext.User.Identity;
                     return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(identity)));  
                 }
             }
      
    4. In the Program.cs ,add (DefaultPolicy make all using Windows Authentication)
         builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
             .AddNegotiate();
         builder.Services.AddAuthorization(options =>
         {
             options.FallbackPolicy = options.DefaultPolicy;
         });
         builder.Services.AddCascadingAuthenticationState();
         builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();
         builder.Services.AddHttpContextAccessor();
      
    5. Modify Home.razor like below
         @page "/"
         @using Microsoft.AspNetCore.Components.Authorization
         @rendermode InteractiveServer
         <h3>User Information</h3>
         <p>Username: @userName</p>
         @code {
             [CascadingParameter]
             private Task<AuthenticationState> authenticationStateTask { get; set; }
             private string userName;
             protected override async Task OnInitializedAsync()
             {
                 var authState = await authenticationStateTask;
                 var user = authState.User;
                 if (user.Identity.IsAuthenticated)
                 {
                     userName = user.Identity.Name;
                 }
                 else
                 {
                     userName = "Anonymous";
                 }
             }
         }
      

    Then you could see the UserName when you run the project.

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".  Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.