Search code examples
asp.net-core-mvcasp.net-core-6.0

ASP.NET Core 6 : get Windows user


I am having a devil of a time getting a simple Windows Domain User in my view in an ASP.NET Core 6 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

I have this in my launchSettings.json:

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

I did also added this code 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


Solution

  • 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.