Get current logged in username from Active Directory? - asp.net

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?

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

Related

ASP.Net Core : get members of Active Directory group

I'm wondering how I could get a list of members of an AD group.
Checking if an entered password of a user is correct works perfectly fine. For this I'm using Novell's Ldap.NetStandard:
private bool IsUserValid(string userName,string userPassword)
{
try{
using (var connection = new LdapConnection { SecureSocketLayer = false })
{
connection.Connect("test.local", LdapConnection.DEFAULT_PORT);
connection.Bind(userDn, userPassword);
if (connection.Bound)
{
return true;
}
}
}
catch (LdapException ex)
{
Console.WriteLine(ex.Massage);
}
return false;
}
What I want now is something like this:
bool isUserInGroup("testUser","testGroup");
The problem is I can't get my method working:
public bool IsUserMemberOfGroup(string userName,string groupName)
{
var ldapConn = GetConnection();
var searchBase = "";
var filter = $"(&(objectClass=group)(cn={groupName}))";
var search = ldapConn.Search(searchBase, LdapConnection.SCOPE_BASE, filter, null, false);
while (search.hasMore())
{
var nextEntry = search.next();
if (nextEntry.DN == userName)
return true;
}
return false;
}
What ever I'm doing, I'm not getting back any value from my Ldap.Search()...
Now there is an implementation of System.DirectoryServices.AccountManagement for .NET Core 2. It is available via nuget.
With this package you are able to things like that:
using (var principalContext = new PrincipalContext(ContextType.Domain, "YOUR AD DOMAIN"))
{
var domainUsers = new List<string>();
var userPrinciple = new UserPrincipal(principalContext);
// Performe search for Domain users
using (var searchResult = new PrincipalSearcher(userPrinciple))
{
foreach (var domainUser in searchResult.FindAll())
{
if (domainUser.DisplayName != null)
{
domainUsers.Add(domainUser.DisplayName);
}
}
}
}
This performs a search for the user in your domain.Nearly the same is possible for searching your group. The way I used to search my AD (description in my question) is now obsolet:
Checking if an entered password of a user is correct works perfectly
fine. For this I'm using Novell's Ldap.NetStandard:
How about:
HttpContext.User.IsInRole("nameOfYourAdGroup");
(namespace System.Security.Claims)

ASP.NET MVC 5 Page Controlled by Active Directory Group

Is it possible to create a page (View) that is strictly controlled by an Active Directory Group?
There is no login for this page, if you are a member of the "VIP" Active Directory group, then the page is rendered, otherwise if not then you can't see it.
First get your current users windows log in
var windowsUserName= HttpContext.Current.User.Identity.WindowsLogin();
Then get all the AD groups for your user using the System.DirectoryServices
using System.DirectoryServices;
public List<string> GetUsersActiveDirectoryGroups(string windowsUserName)
{
try
{
var allUserGroups = new List<string>();
if (windowsUserName == null) return allUserGroups;
var domainConnection = new DirectoryEntry();
var samSearcher = new DirectorySearcher
{
SearchRoot = domainConnection,
Filter = "(samAccountName=" + windowsUserName + ")"
};
samSearcher.PropertiesToLoad.Add("displayName");
var samResult = samSearcher.FindOne();
if (samResult == null) return allUserGroups;
var theUser = samResult.GetDirectoryEntry();
theUser.RefreshCache(new[] { "tokenGroups" });
_bet365EmployeeFullName = theUser.Properties["CN"].Value.ToString();
foreach (byte[] resultBytes in theUser.Properties["tokenGroups"])
{
var mySid = new SecurityIdentifier(resultBytes, 0);
var sidSearcher = new DirectorySearcher
{
SearchRoot = domainConnection,
Filter = "(objectSid=" + mySid.Value + ")"
};
sidSearcher.PropertiesToLoad.Add("name");
var sidResult = sidSearcher.FindOne();
if (sidResult != null)
{
allUserGroups.Add((string)sidResult.Properties["name"][0]);
}
}
return allUserGroups;
}
You now need to map which groups have access to which view in the application.
Once done, the next step is the restricting of the viewing of "Views".
You need to set up a permissions filter that uses the MVC AuthorizeAttribute. Something like the below.
public class PermissionsFilter : AuthorizeAttribute
{
private readonly string _viewName;
public PermissionsFilter(string viewName)
{
_viewName = viewName;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
//Check to see if users groups has access to the view
//If not redirect to unauthorized page
}
}
I accomplish the above by have a user object held in session. This contains a list of all the application permissions my user has access too. This is the mapping you need to do. I have all my view names stored in the database along with an ID of which AD groups can access them.
Then finally in the controller, decorate the get action for the view accordingly.
[HttpGet]
[PermissionsFilter("ViewName")]
public ActionResult ReturnMyView(int currentFolderID)
{
return View(); //Etc..
}
Well hope that helps!

EF - Seed function not updating table

In asp.net webform application, trying to save user to AspNetUsers after UPDATE-DATABASE command. the following code doesnt do that. solution ?
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(MyApp.Models.ApplicationDbContext context)
{
if (!context.Users.Any(u => u.Email == "some#mail"))
{
var store = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(store);
var user = new ApplicationUser { Email = "some#mail" };
manager.Create(user, "password");
}
}
In order to add ApplicationUser you must have the property Username initialized.

asp.net active directory intranet

I have an intranet that gets the current logged in user through active directory. When a user is locked out they get a windows prompt to enter their username and password. Is there a way for me to catch this and redirect them to a page where they are asked to enter their credentials again or tell them that their account might be locked out and to contact the help desk?
On your application once you grab the user that is logged in do the IsAccountLocked method below
public bool IsAccountLocked(string sUserName)
{
UserPrincipal oUserPrincipal = GetUser(sUserName);
return oUserPrincipal.IsAccountLockedOut();
}
public UserPrincipal GetUser(string sUserName)
{
PrincipalContext oPrincipalContext = GetPrincipalContext();
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
return oUserPrincipal;
}
public PrincipalContext GetPrincipalContext()
{
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sDefaultOU, ContextOptions.SimpleBind, sServiceUser, sServicePassword);
return oPrincipalContext;
}
This is using System.DirectoryServices.AccountManagement for using only System.DirectoryServices you can do this
public bool IsAccountLocked(DirectoryEntry oDE)
{
return Convert.ToBoolean(oDE.InvokeGet("IsAccountLocked"));
}
public DirectoryEntry GetUser(string sUserName)
{
//Create an Instance of the DirectoryEntry
oDE = GetDirectoryObject();
//Create Instance fo the Direcory Searcher
oDS = new DirectorySearcher();
oDS.SearchRoot = oDE;
//Set the Search Filter
oDS.Filter = "(&(objectClass=user)(sAMAccountName=" + sUserName + "))";
oDS.SearchScope = SearchScope.Subtree;
oDS.PageSize = 10000;
//Find the First Instance
SearchResult oResults = oDS.FindOne();
//If found then Return Directory Object, otherwise return Null
if (oResults != null)
{
oDE = new DirectoryEntry(oResults.Path, sADUser, sADPassword, AuthenticationTypes.Secure);
return oDE;
}
else
{
return null;
}
}
private DirectoryEntry GetDirectoryObject()
{
oDE = new DirectoryEntry(sADPath, sADUser, sADPassword, AuthenticationTypes.Secure);
return oDE;
}
for a full implementation you can go to
http://anyrest.wordpress.com/2010/06/28/active-directory-c/
or
http://anyrest.wordpress.com/2010/02/01/active-directory-objects-and-c/

Get Full name from Windows Authentication in ASP.Net BLL class

Trying to figure out how to get the current User's Full Name as entered in Active Directory from a BLL class in my ASP.Net application. So far I have:
public static string Username
{
get
{
var name = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if (name.Contains("\\"))
{
var start = name.IndexOf("\\");
if (name.Length > start)
{
name = name.Substring(start + 1);
}
}
return name;
}
}
The problem with this is that this will return the Username, but I am also in need of the Full Name. Anyone know if this is possible?
Use a DirectorySearcher ...
var search = new DirectorySearcher( new DirectoryEntry("LDAP://YourDomain") );
search.Filter = "(sAMAccountName=UserNameHere)"; // put the identity name here
var res = search.FindOne();
var name = res["displayName"]; // I believe this is the right property

Resources