Search code examples
asp.netauthenticationweb-applicationsactive-directoryaudit

Get current logged in username from Active Directory?


My web application uses Active Directory Authentication when a user logs in. I use the following code for audit columns. It works perfectly fine for the CreatedAt and ModifiedAt dates but the currentUsername is hardcoded.

    public override int SaveChanges()
    {
        var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseClass && (x.State == EntityState.Added || x.State == EntityState.Modified));
        var currentUsername = "T";
        foreach (var entity in entities)
        {
            if (entity.State == EntityState.Added)
            {
                ((BaseClass)entity.Entity).CreatedAt = DateTime.Now;
                ((BaseClass)entity.Entity).CreatedBy = currentUsername;
            }
            ((BaseClass)entity.Entity).ModifiedAt = DateTime.Now;
            ((BaseClass)entity.Entity).ModifiedBy = currentUsername;
        }
        return base.SaveChanges();
    }

How can I get the current username logged in Active Directory?


Solution

  • If you're on .NET 4.5 or higher, just use the System.DirectoryServices.AccountManagement namespace and the UserPrincipal class in that context:

    // you'll need to add a reference to this .NET assembly in your project
    // so that you can use this namespace
    using System.DirectoryServices.AccountManagement;
    
    public string GetLoggedInUser()
    {
        // establish the PrincipalContext - this will grab the default domain, default containers
        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
        {
             // get the currently active user
             UserPrincipal currentUser = UserPrincipal.Current;
    
             if (currentUser != null)
             {
                 // this will return "first name last name" separated by a space,
                 // e.g. "John Doe" or "Jane Tarzan" 
                 return $"{currentUser.GivenName} {currentUser.Surname}";
             }
        }
    
        return string.Empty;  
    }