5

I have been searching here on who else has this issue with getting the User info from HttpContextAccessor.HttpContext.User.Identiy.Name

but it is always null.

I am using .net api core v5 and in my startup.cs

public void ConfigureServices(IServiceCollection services) { services.AddHttpContextAccessor(); ... services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseCors(AllowedOrigins); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } 

In my visual studio launchSettings.json

{ "iisSettings": { "windowsAuthentication": true, "anonymousAuthentication": true, // also turned it to false to test "iisExpress": { "applicationUrl": "http://localhost:55555/", "sslPort": 44444 } }, ... } 

Here is my Controller with test code to get the user info

public class MyController : ControllerBase { private readonly IHttpContextAccessor httpContextAccessor; public MyController (IHttpContextAccessor _httpContextAccessor) { httpContextAccessor = _httpContextAccessor; } [HttpGet] public async Task<ActionResult<ReturnDto>> GetTestData() { string userName = httpContextAccessor.HttpContext.User.Identity.Name; // also try to get user from ControllerBase var ControllerBaseName = this.User; Both of these test result are null. return Ok(); } } 

I cannot figure out why the HttpContext user is always null. I read a few post here but my startup.cs is the same. Another user said try ControllerBase.User but that is null too. I am testing this with my Visual Studio debugger

Is there another easier way to get the logged in userID?

Any help is appreciated. Thanks

2 Answers 2

3

Are you configuring the authentication service to use Windows Auth?

services.AddAuthentication(IISDefaults.AuthenticationScheme); 

more info here: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-5.0

Sign up to request clarification or add additional context in comments.

Comments

3

Figured it out, web.config authenication settings to get HttpContext user name to show

 <authentication> <anonymousAuthentication enabled="false" /> <windowsAuthentication enabled="true" /> </authentication> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.