0

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 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"
      }
    }
  }
}

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>();
                });
    }
}

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

any help will be highly appreciated.

rimi
  • 624
  • 5
  • 15
  • Have you tried using [`UserPrincipal.Current`](https://learn.microsoft.com/en-us/dotnet/api/system.directoryservices.accountmanagement.userprincipal.current?view=dotnet-plat-ext-7.0#system-directoryservices-accountmanagement-userprincipal-current) to get the current user (which the code is running as)? – marc_s Mar 01 '23 at 05:57

1 Answers1

0

try using

System.Web.HttpContext.Current.User.Identity.Name 

instead of

WindowsIdentity.GetCurrent().Name

note : (out of the question) you can simplify your function as :

public static UserPrincipal GetADUserInfo(string userName)
{
    using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
    {
        return UserPrincipal.FindByIdentity(ctx, userName);
    }
}
tuyau2poil
  • 767
  • 1
  • 2
  • 7
  • System.Web.HttpContext.Current.User.Identity.Name is always NULL. I padsted my program.cs and startup.cs file. – rimi Mar 02 '23 at 04:03