Value is always null using User.Identity.Name

Anna Olson 0 Reputation points
2023-07-28T16:22:45.25+00:00

I have an ASP.NET React website and I want to get current logged in Windows user, I use the following codes in my controller but it always gives me null. I've got stuck for a long time and any help with this will be highly appreciated.

[HttpGet("currentUser")]
        public ActionResult GetCurrentUser()
        {
            if (User.Identity.IsAuthenticated)
            {
                // Get the Windows username
                string windowsUsername = User.Identity.Name;
               
                return Content("Windows Username: " + windowsUsername);
            }
            else
            {
                // Not authenticated using Windows Authentication.
                return Content("User not authenticated.");
            }
        }

This is my program.cs file:

using Microsoft.EntityFrameworkCore;
using PslProcEng.Data;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.AspNetCore.Authentication.Negotiate;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.FileProviders;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.DependencyInjection;


var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddHttpContextAccessor();
builder.Services.AddControllers();
builder.Services.AddControllersWithViews();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddDbContext<InternTestDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddDbContext<TrainingVisionContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("TrainingVisionConnection")));
builder.Services.AddDbContext<UserListContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("UserListConnection")));
builder.Services.AddControllers().AddNewtonsoftJson();
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = NegotiateDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = NegotiateDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
    .AddNegotiate()
    .AddCookie();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

var app = builder.Build();


// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(Path.Combine(
    AppDomain.CurrentDomain.BaseDirectory)),
});

app.UseRouting();
app.MapControllers();

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

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html"); ;

app.Run();


this is my launchSettings.json file:

{
  "profiles": {
    "Project1": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      },
      "applicationUrl": "http://mywebsite.com"
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    }
  },
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://mywebsite.com",
      "sslPort": 44381
    }
  }
}
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,025 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,186 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,982 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Ruikai Feng - MSFT 2,506 Reputation points Microsoft Vendor
    2023-07-31T02:35:50.6766667+00:00

    Hi,@Anna Olson,

    Please try as below;

    Right click on your project=>Properties=>Debug

    Check if you've enabled Windows Authentication and disabled Anonymous Authentication

    User's image

    I tried to reproduce the issue with your settings,

    When I enable both:

    User's image

    just enable Windows Authentication:

    User's image

    For Kestrel,the codes below are required:

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

    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.

    Best regards,

    Ruikai Feng