Get AD Guid from HttpContext.Current.User - asp.net-mvc-4

I have tried many, many different ways, to get this data. But I can't get it to work.
I have a MVC4 application, hooked up with Active Directory. But I need the users AD GUID.
I tried:
(Guid)Membership.GetUser(User.Identity.Name).ProviderUserKey;
WebSecurity.CurrentUserId;
But none of them work.

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, User.Identity.Name);
if(user != null)
{
Guid userGuid = user.Guid ?? Guid.Empty;
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!

I managed to solve it (Not pretty...):
string login = HttpContext.Current.User.Identity.Name;
string domain = login.Substring(0, login.IndexOf('\\'));
string userName = login.Substring(login.IndexOf('\\') + 1);
DirectoryEntry domainEntry = new DirectoryEntry("LDAP://" + domain);
DirectorySearcher searcher = new DirectorySearcher(domainEntry);
searcher.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))",userName);
SearchResult searchResult = searcher.FindOne();
DirectoryEntry entry = searchResult.GetDirectoryEntry();
Guid objectGuid = entry.Guid;
The original code used : entry.NativeGuid, but I changed because of Little / Big endian "problems"
entry.Guid has the same "format" as in AD.

Related

ASP.NET Active Directory Search

I'm trying to create an intranet Website on ASP.NET MVC 4 using Windows Login. I have successfully done the windows login. The only thing I am stuck up with is searching the active directory with partial username. I tried searching the web and stackoverflow website but still couldn't find the answer.
DirectoryEntry directory = new DirectoryEntry("LDAP://DC=NUAXIS");
string filter = "(&(cn=jinal*))";
string[] strCats = { "cn" };
List<string> items = new List<string>();
DirectorySearcher dirComp = new DirectorySearcher(directory, filter, strCats, SearchScope.Subtree);
SearchResultCollection results = dirComp.FindAll();
You can use a PrincipalSearcher and a "query-by-example" principal to do your searching:
// create your domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// define a "query-by-example" principal - here, we search for a UserPrincipal
// and with the first name (GivenName) of "Jinal*"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.GivenName = "Jinal*";
// create your principal searcher passing in the QBE principal
using (PrincipalSearcher srch = new PrincipalSearcher(qbeUser))
{
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" -
// it could be user, group, computer.....
}
}
}
If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement. Or see the MSDN documentation on the System.DirectoryServices.AccountManagement namespace.
Of course, depending on your need, you might want to specify other properties on that "query-by-example" user principal you create:
DisplayName (typically: first name + space + last name)
SAM Account Name - your Windows/AD account name
User Principal Name - your "username#yourcompany.com" style name
You can specify any of the properties on the UserPrincipal and use those as "query-by-example" for your PrincipalSearcher.
Your current code is on the right track.
I think you had your wildcard backwards.
Consider this:
search.Filter = string.Format("(&(sn={0}*)(givenName={1}*)(objectSid=*))", lastName, firstName);

Multiple sessions with Fluent NHibernate and Ninject

I am working on setting up a multi-tenant, seperate database application and have made some good progress from reading this post below on stackoverflow.
Multitenancy with Fluent nHibernate and Ninject. One Database per Tenant
I see two sessions being setup. One is the 'master' session that will be used to get the tenant information and then the tenant session which is specific to the subdomain. I have the app switching nicely to the specified database based on domain and have questions on how to setup the 'master' database session and how to use it.
I tried registering a new session specifically for the master session be get an error regarding having already registered an ISession.
I'm new to nHibernate and not sure the best route to take on this.
NinjectWebCommon.cs
kernel.Bind<WebApplication1.ISessionSource>().To<NHibernateTenantSessionSource>().InSingletonScope();
kernel.Bind<ISession>().ToMethod(c => c.Kernel.Get<WebApplication1.ISessionSource>().CreateSession());
kernel.Bind<ITenantAccessor>().To<DefaultTenantAccessor>();
ITenantAccessor.cs
public Tenant GetCurrentTenant()
{
var host = HttpContext.Current.Request.Url != null ? HttpContext.Current.Request.Url.Host : string.Empty;
var pattern = ConfigurationManager.AppSettings["UrlRegex"];
var regex = new Regex(pattern);
var match = regex.Match(host);
var subdomain = match.Success ? match.Groups[1].Value.ToLowerInvariant() : string.Empty;
Tenant tenant = null;
if (subdomain != null)
{
// Get Tenant info from Master DB.
// Look up needs to be cached
DomainModel.Master.Tenants tenantInfo;
using (ISession session = new NHibernateMasterSessionSource().CreateSession())
{
tenantInfo = session.CreateCriteria<DomainModel.Master.Tenants>()
.Add(Restrictions.Eq("SubDomain", subdomain))
.UniqueResult<WebApplication1.DomainModel.Master.Tenants>();
}
var connectionString = string.Format(ConfigurationManager.AppSettings["TenanatsDataConnectionStringFormat"],
tenantInfo.DbName, tenantInfo.DbUsername, tenantInfo.DbPassword);
tenant = new Tenant();
tenant.Name = subdomain;
tenant.ConnectionString = connectionString;
}
return tenant;
}
Thanks for you time on this.
Add another session binding and add some condition. E.g.
kernel
.Bind<ISession>()
.ToMethod(c => c.Kernel.Get<NHibernateMasterSessionSource>().CreateSession())
.WhenInjectedInto<TenantEvaluationService>();

how to access Active directory from WCF service

I've been asked to create a service in WCF, where input is user EMAIL-ID. there are many domains available in my server. My WCF service is hosted in xxx domain.
I need to get all yyy groups (Domain groups) for the user whose email matches.
Questions:
1. Can we connect to the Active directory from C#
2. How to get the User groups from C#.
3. It is just for user validation, there is nothing to do with Active Directory. (simple search in AD groups)
Since I'm new to this, even I dont know wheather it is possoble from C#. Early reply on this is highly appreciable. Thanks in advance.
The System.DirectoryServices.AccountManagement namespace is exactly what you need.
Here's some code that should get you started.
using System;
using System.DirectoryServices.AccountManagement;
namespace TestADCSharp
{
class Program
{
static void Main(string[] args)
{
PrincipalContext p = new PrincipalContext(
ContextType.Domain,
"your.domain"
);
UserPrincipal u = new UserPrincipal(p);
u.EmailAddress = "your#search.email";
PrincipalSearcher ps = new PrincipalSearcher(u);
PrincipalSearchResult<Principal> results = ps.FindAll();
foreach (Principal r in results) {
PrincipalSearchResult<Principal> groups = r.GetGroups();
Console.WriteLine("Groups:");
foreach (Principal g in groups) {
Console.WriteLine("\t" + g.Name);
}
}
}
}
}

Adding users to AD using LDAP

I'm writing an application that will add users to Active Directory. I'm trying to use this code to connect to the "Users" shared folder in AD
LDAP://celtestdomdc1.celtestdom.local/CN=Users,DC=celtestdom,DC=local
However it adds the user in with the shared folders, instead of within the "Users" shared folder. Shouldn't CN=Users mean it will add it to the "Users" folder?
Thanks
If you're creating a user, you need to
bind to the container you want to create the user in
create the new user account as a child of that container
Just by setting the LDAP path, you are not defining where the user will go!
Try something like this (C# sample - should be trivial to convert to VB.NET):
DirectoryEntry cnUsers = new DirectoryEntry("LDAP://CN=Users,DC=celtestdom,DC=local");
// create a user directory entry in the container
DirectoryEntry newUser = container.Children.Add("cn=NewUserAccount", "user");
// add the samAccountName mandatory attribute
newUser.Properties["sAMAccountName"].Value = "NewUser";
// add any optional attributes
newUser.Properties["givenName"].Value = "User";
newUser.Properties["sn"].Value = "One";
// save to the directory
newUser.CommitChanges();
// set a password for the user account
// using Invoke method and IadsUser.SetPassword
newUser.Invoke("SetPassword", new object[] { "pAssw0rdO1" });
// require that the password must be changed on next logon
newUser.Properties["pwdLastSet"].Value = 0;
// save to the directory
newUser.CommitChanges();
Or if you're using .NET 3.5 or newer, you could also use the new System.DirectoryServices.AccountManagement namespace that makes lots of things easier.
Then the code looks a bit simpler:
// create a context for a domain and define "base" container to use
PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
"celtestdom", "CN=Users,DC=celtestdom,DC=local");
// create a user principal object
UserPrincipal user = new UserPrincipal(ctx, "NewUser", "pass#1w0rd01", true);
// assign some properties to the user principal
user.GivenName = "User";
user.Surname = "One";
// force the user to change password at next logon
user.ExpirePasswordNow();
// save the user to the directory
user.Save();
Check out more about the System.DirectoryServices.AccountManagement (S.DS.AM) namespace here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement

Simple login for multi-domain intranet?

I have an intranet server on a Windows domain (server is Windows 2003, IIS6, NTFS permissions). It is on the domain Domain01. I have users from two domains in the same forest that access this intranet: Domain01 and Domain02 (DCs also running Windows 2003). Currently, the users are required to login by entering either:
Domain01\username or username#Domain01
My users are completely and thoroughly confused by having to enter the domain each time they log in.
Is there any way to simply allow them to log in by entering just their username and password WITHOUT the domain? For example, have the server try Domain01 by default, and if the login fails to try Domain02?
NOTE: I would like to do this via IIS or server settings if possible, rather than programmatically (for reference, I am using ASP.NET 2.0).
Yes. Usually what I do is do a global catalog search using the supplied user name as the sAMAccountName. Doing this with a PrincipalSearcher requires getting the underlying DirectorySearcher and replacing it's SearchRoot. Once I find the corresponding user object I extract the domain from the user object's path and use that as the domain for the authentication step. How you do the authentication varies depending on what you need it to do. If you don't need impersonation you can use PrincipalContext.ValidateCredentials to make sure that the username/password match using a PrincipalContext that matches the domain of the user account that you previously found. If you need impersonation check out this reference.
// NOTE: implement IDisposable and dispose of this if not null when done.
private DirectoryEntry userSearchRoot = null;
private UserPrincipal FindUserInGlobalContext( string userName )
{
using (PrincipalSearcher userSearcher = new PrincipalSearcher())
{
using (PrincipalContext context
= new PrincipalContext( ContextType.Domain ))
{
userSearcher.QueryFilter = new UserPrincipal( context );
DirectorySearcher searcher
= (DirectorySearcher)userSearcher.GetUnderlyingSearcher();
// I usually set the GC path from the existing search root
// by doing some string manipulation based on our domain
// Your code would be different.
string GCPath = ...set GC path..
// lazy loading of the search root entry.
if (userSearchRoot == null)
{
userSearchRoot = new DirectoryEntry( GCPath );
}
searcher.SearchRoot = userSearchRoot;
using (PrincipalContext gcContext =
new PrincipalContext( ContextType.Domain,
null,
GCPath.Replace("GC://",""))
{
UserPrincipal userFilter = new UserPrincipal( gcContext );
userFilter.SamAccountName = userName;
userSearcher.QueryFilter = userFilter;
return userSearcher.FindOne() as UserPrincipal;
}
}
}
}