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:
- Create a Blazor Web App project. (no authentication, Server, global)
- Install
Microsoft.AspNetCore.Authentication.Negotiate
- 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))); } }
- 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();
- 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.
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.