Home > Software engineering >  asp.net 6 Get Windows User
asp.net 6 Get Windows User

Time:06-22

I am having a devil of a time getting a simple Windows Domain User in my view in a apsnet core MVC project. Looking in google, i see a lot of people having the same question but very few suggestions past a full auth system. I was just hoping to turn on windows auth and get a username, no need for any other functions then to just display a name in the view.

In the past I have used:

@User.Identity.Name

in my launchSettings.json:

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,

I did also added to Program.cs:

app.UseAuthentication();
app.UseAuthorization();

Is there no way to just grab the windows user for a display value in asp.net core 6

CodePudding user response:

In my opinion,you should have authentication to get UserName,you need to Enable Windows Authentication.

Program.cs:

builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy.
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddHttpContextAccessor();
app.UseAuthentication();
app.UseAuthorization();

launchSettings.json:

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
}

Controller:

string UserName = HttpContext.User.Identity.Name;

Test Result:

enter image description here

For more details,please check this link.

If you do not need to automaticaly login the user with Windows Authentication, and you have already a custom login Controller to do that,you can refer to this.

  • Related