value is always null when using HttpContext.User.Identity.Name

Anjali Agarwal 1,366 Reputation points
2023-03-02T03:53:54.1166667+00:00

Hello,

I am trying to get the value in x and y variable from window.security and HTTPContext, but not sure

what am I doing wrong that the value is always NULL.

var x = System.Security.Principal.WindowsPrincipal.Current.Identity.Name;

var y = HttpContext.User.Identity.Name;

Below is my program.cs file:

using AckPackage;

using Microsoft.AspNetCore.Hosting;

using Microsoft.Extensions.Hosting;

namespace TrustedSystem

{

public class Program

{

    public static void Main(string[] args)

    {

        CreateHostBuilder(args).Build().Run();

    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>

        Host.CreateDefaultBuilder(args)

            .ConfigureWebHostDefaults(webBuilder =>

            {

                webBuilder.UseStartup<Startup>();

            });

}

}

below is my startup.cs file:


using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Authentication;

using Microsoft.AspNetCore.Authentication.Cookies;

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Mvc.Authorization;

using Microsoft.AspNetCore.Server.IISIntegration;

using Microsoft.Extensions.Configuration;

using Microsoft.AspNetCore.Http;

using Microsoft.Extensions.Configuration;

using Microsoft.EntityFrameworkCore;

using AckPackage.Data;

using AckPackage.Models;

using AckPackage.Extensions;

using System.Net;

using Microsoft.Extensions.DependencyInjection;

namespace AckPackage

{

public class Startup

{

    public IConfiguration Configuration { get; }

    private const string DefaultConnection = "DefaultConnection";

    public Startup(IConfiguration configuration)

    {

        Configuration = configuration;

    }

    public void ConfigureServices(IServiceCollection services)

    {

        services.AddDbContext<AckPackage.Data.AckContext>(options =>

            options.UseSqlServer(

                Configuration.GetConnectionString(DefaultConnection)));

        services.Configure<CookiePolicyOptions>(options =>

        {

            // This lambda determines whether user consent for non-essential cookies is needed for a given request.

            options.CheckConsentNeeded = context => true;

            options.MinimumSameSitePolicy = SameSiteMode.None;

        });

        services.AddAuthentication(options =>

        {

            options.DefaultAuthenticateScheme = IISDefaults.AuthenticationScheme;

            options.DefaultChallengeScheme = IISDefaults.AuthenticationScheme;

        });  //.AddNegotiate();

        services.AddAuthorization();

        //services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)

        //.AddCookie(options =>

        //{

        //    options.LoginPath = "/Employee/Create";

        //});

        services.AddHttpContextAccessor();

        services.AddControllersWithViews();

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddDistributedMemoryCache();

        services.AddSession(options =>

        {

            options.IdleTimeout = TimeSpan.FromSeconds(120);

            options.Cookie.HttpOnly = true;

            options.Cookie.IsEssential = true;

        });

        services.AddRazorPages();

        //services.AddMvc().AddRazorRuntimeCompilation();

        services.BindingAppServices(Configuration);

        services.Configure<Microsoft.AspNetCore.Http.Features.FormOptions>(x =>

        {

            x.ValueLengthLimit = int.MaxValue;

            x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart

        });

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

    {

        if (env.IsDevelopment())

        {

            app.UseDeveloperExceptionPage();

        }

        else

        {

            app.UseExceptionHandler("/Home/Error");

            // The default HSTS value is 30 days.

            app.UseHsts();

        }

        app.UseHttpsRedirection();

        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseSession();

        app.UseEndpoints(endpoints =>

        {

            endpoints.MapControllerRoute(

                name: "default",

                pattern: "{controller=Employee}/{action=Create}/{id?}");

            endpoints.MapRazorPages();

        });

        // app.MapRazorPages();

    }

}

}

below is my launchsettings.cs file

{
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:10222",
      "sslPort": 44314
    }
  },
  "profiles": {
    "AckPackage": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7043;http://localhost:6043",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

I am using .net core 6.0 I am struggling with this issue for past 2 days and could not resolve it. This value is null on my local machine. I haven't deployed the code to server yet.

if I add "addnegotiate" in below code:

 services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = IISDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = IISDefaults.AuthenticationScheme;
            }).AddNegotiate();

then i get an error in program.cs at this line saying:

public static void Main(string[] args)
        {
            CreateBuilder(args).Build().Run();
        }
saying:

System.IO.FileNotFoundException
  HResult=0x80070002
  Message=Could not load file or assembly 'System.DirectoryServices.Protocols, Version=6.0.0.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
  Source=Microsoft.AspNetCore.Authentication.Negotiate

any help with this will be highly appreciated.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,192 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,276 questions
{count} votes

Accepted answer
  1. Rena Ni - MSFT 2,061 Reputation points
    2023-03-02T07:21:14.98+00:00

    Hi @Anjali Agarwal,

    Firstly, the correct way to get the name by WindowsPrincipal should be like below:

    WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
    
    var username = wp.Identity.Name;
    

    Secondly, be sure the anonymousAuthentication value is set false in your launchSettings.json(located in Properties folder).

    Thirdly, change your Startup.cs like below if you use .NET6:

    services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
        .AddNegotiate();
    services.AddAuthorization(options =>
    {
        options.FallbackPolicy = options.DefaultPolicy;   
    });
    

    At last, clean the project(right-click the project and choose Clean) and then run the application.


    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,

    Rena

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful