Search Results

Search found 25 results on 1 pages for 'principalcontext'.

Page 1/1 | 1 

  • AD - Using UserPrincipal.FindByIdentity and PrincipalContext with nested OU - C#

    - by Solid Snake
    Here is what I am trying to achieve: I have a nested OU structure that is about 5 levels deep. OU=Portal,OU=Dev,OU=Apps,OU=Grps,OU=Admin,DC=test,DC=com I am trying to find out if the user has permissions/exists at OU=Portal. Here's a snippet of what I currently have: PrincipalContext domain = new PrincipalContext( ContextType.Domain, "test.com", "OU=Portal,OU=Dev,OU=Apps,OU=Grps,OU=Admin,DC=test,DC=com"); UserPrincipal user = UserPrincipal.FindByIdentity(domain, myusername); PrincipalSearchResult<Principal> group = user.GetAuthorizationGroups(); For some unknown reason, the value user generated from the above code is always null. However, if I were to drop all the OU as follows: PrincipalContext domain = new PrincipalContext( ContextType.Domain, "test.com", "DC=test,DC=com"); UserPrincipal user = UserPrincipal.FindByIdentity(domain, myusername); PrincipalSearchResult<Principal> group = user.GetAuthorizationGroups(); this would work just fine and return me the correct user. I am simply trying to reduce the number of results as opposed to getting everything from AD. Is there anything that I am doing wrong? I've googled for hours and tested various combinations without much luck. Any help is appreciated. Thanks. Dan

    Read the article

  • Active Directory Services: PrincipalContext -- What is the DN of a "container" object?

    - by Ranger Pretzel
    I'm currently trying to authenticate via Active Directory Services using the PrincipalContext class. I would like to have my application authenticate to the Domain using Sealed and SSL contexts. In order to do this, I have to use the following constructor of PrincipalContext (link to MSDN page): public PrincipalContext( ContextType contextType, string name, string container, ContextOptions options ) Specifically, I'm using the constructor as so: PrincipalContext domainContext = new PrincipalContext( ContextType.Domain, domain, container, ContextOptions.Sealing | ContextOptions.SecureSocketLayer); MSDN says about "container": The container on the store to use as the root of the context. All queries are performed under this root, and all inserts are performed into this container. For Domain and ApplicationDirectory context types, this parameter is the distinguished name (DN) of a container object. What is the DN of a container object? How do I find out what my container object is? Can I query the Active Directory (or LDAP) server for this?

    Read the article

  • How to Authenticate to Active Directory Services (ADs) using .NET 3.5 / C#

    - by Ranger Pretzel
    After much struggling, I've figured out how to authenticate to my company's Active Directory using just 2 lines of code with the Domain, Username, and Password in .NET 2.0 (in C#): // set domain, username, password, and security parameters DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, username, password, AuthenticationTypes.Secure | AuthenticationTypes.SecureSocketsLayer); // force Bind to AD server to authenticate object obj = entry.NativeObject; If the 2nd line throws an exception, then the credentials and/or parameters were bad. (Specific reason can be found in the exception.) If no exception, then the credentials are good. Trying to do this in .NET 3.5 looks like it should be easy, but has me at a roadblock instead. Specifically, I've been working with this example: PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domain); using (domainContext) { return domainContext.ValidateCredentials(UserName, Password); } Unfortunately, this doesn't work for me as I don't have both ContextOptions set to Sealed/Secure and SSL (like I did above in the .NET 2.0 code.) There is an alternate constructor for PrincipalContext that allows setting the ContextOptions, but this also requires supplying a Distinguished Name (DN) of a Container Object and I don't know exactly what mine is or how I would find out. public PrincipalContext(ContextType contextType, string name, string container, ContextOptions options); // container: // The container on the store to use as the root of the context. All queries // are performed under this root, and all inserts are performed into this container. // For System.DirectoryServices.AccountManagement.ContextType.Domain and System.DirectoryServices.AccountManagement.ContextType.ApplicationDirectory // context types, this parameter is the distinguished name of a container object. Any suggestions?

    Read the article

  • DirectoryServicesCOMException when working with System.DirectoryServices.AccountManagement

    - by antik
    I'm attempting to determine whether a user is a member of a given group using System.DirectoryServices.AccountManagment. I'm doing this inside a SharePoint WebPart in SharePoint 2007 on a 64-bit system. Project targets .NET 3.5 Impersonation is enabled in the web.config. The IIS Site in question is using an IIS App Pool with a domain user configured as the identity. I am able to instantiate a PrincipalContext as such: PrincipalContext pc = new PrincipalContext(ContextType.Domain) Next, I try to grab a principal: using (PrincipalContext pc = new PrincipalContext(ContextType.Domain)) { GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, "MYDOMAIN\somegroup"); // snip: exception thrown by line above. } Both the above and UserPrincipal.FindByIdentity with a user SAM throw a DirectoryServicesCOMException: "Logon failure: Unknown user name or bad password" I've tried passing in a complete SAMAccountName to either FindByIdentity (in the form of MYDOMAIN\username) or just the username with no change in behavior. I've tried executing the code with other credentials using both the HostingEnvironment.Impersonate and SPSecurity.RunWithElevatedPrivileges approaches and also experience the same result. I've also tried instantiating my context with the domain name in place: Principal Context pc = new PrincipalContext(ContextType.Domain, "MYDOMAIN"); This throws a PrincipalServerDownException: "The server could not be contacted." I'm working on a reasonably hardened server. I did not lock the system down so I am unsure exactly what has been done to it. If there are credentials I need to allocate to my pool identity's user or in the domain security policy in order for these to work, I can configure the domain accordingly. Are there any settings that would be preventing my code from running? Am I missing something in the code itself? Is this just not possible in a SharePoint web? EDIT: Given further testing, my code functions correctly when tested in a Console application targeting .NET 4.0. I targeted a different framework because I didn't have AccountManagement available to me in the console app when targeting .NET 3.5 for some reason. using (PrincipalContext pc = new PrincipalContext(ContextType.Domain)) using (UserPrincipal adUser = UserPrincipal.FindByIdentity(pc, "MYDOMAIN\joe.user")) using (GroupPrincipal adGroup = GroupPrincipal.FindByIdentity(pc, "MYDOMAIN\user group")) { if (adUser.IsMemberOf(adGroup)) { Console.WriteLine("User is a member!"); } else { Console.WriteLine("User is NOT a member."); } } What varies in my SharePoint environment that might prohibit this function from executing?

    Read the article

  • Fast way to get a list of group members in Active Directory with C#

    - by Jeremy
    In a web app, we're looking to display a list of sam accounts for users that are a member of a certain group. Groups could have 500 or more members in many cases and we need the page to be responsive. With a group of about 500 members it takes 7-8 seconds to get a list of sam accounts for all members of the group. Are there faster ways? I know the Active Directory Management Console does it in under a second. I've tried a few methods: 1) PrincipalContext pcRoot = new PrincipalContext(ContextType.Domain) GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcRoot, "MyGroup"); List<string> lst = grp.Members.Select(g => g.SamAccountName).ToList(); 2) PrincipalContext pcRoot = new PrincipalContext(ContextType.Domain) GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcRoot, "MyGroup"); PrincipalSearchResult<Principal> lstMembers = grp.GetMembers(true); List<string> lst = new List<string>(); foreach (Principal member in lstMembers ) { if (member.StructuralObjectClass.Equals("user")) { lst.Add(member .SamAccountName); } } 3) PrincipalContext pcRoot = new PrincipalContext(ContextType.Domain) GroupPrincipal grp = GroupPrincipal.FindByIdentity(pcRoot, "MyGroup"); System.DirectoryServices.DirectoryEntry de = (System.DirectoryServices.DirectoryEntry)grp.GetUnderlyingObject(); List<string> lst = new List<string>(); foreach (string sDN in de.Properties["member"]) { System.DirectoryServices.DirectoryEntry deMember = new System.DirectoryServices.DirectoryEntry("LDAP://" + sDN); lst.Add(deMember.Properties["samAccountName"].Value.ToString()); }

    Read the article

  • Request a user's roles in AD when caller is not in domain

    - by grootjans
    I would like to get a user's group memberships in an ActiveDirectory, without being in the domain. When I run this inside the domain, all is well. var context = new PrincipalContext(ContextType.Domain); var principal = UserPrincipal.FindByIdentity(context, IdentityType.Name, "administrator"); foreach (var authorizationGroup in principal.GetAuthorizationGroups()) { Console.WriteLine(authorizationGroup.Name); } However, when I run outside the domain, I have to specify the PrincipalContext lie this: var context = new PrincipalContext(ContextType.Domain, "10.0.1.255", "DC=test,DC=ad,DC=be", "administrator", "password"); When I run this code, I get an exception when I execute principal.GetAuthorizationGroups(). The exception I get is: System.DirectoryServices.AccountManagement.PrincipalOperationException: Information about the domain could not be retrieved (1355). at System.DirectoryServices.AccountManagement.Utils.GetDcName(String computerName, String domainName, String siteName, Int32 flags) at System.DirectoryServices.AccountManagement.ADStoreCtx.LoadDomainInfo() at System.DirectoryServices.AccountManagement.ADStoreCtx.get_DnsDomainName() at System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOfAZ(Principal p) at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroupsHelper() at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroups()

    Read the article

  • C# : Error while accessing Active Directory

    - by Mohsan
    hi. i am facing some problems in accessing Active Directory from my winform app. what I want is to create a user and query user from Active Directory. here is code snippet for find user public bool FindUser(string username) { using (PrincipalContext context = new PrincipalContext(ContextType.Domain, this.domainName, this.DomainUserName, this.DomainPassword)) { UserPrincipal user = UserPrincipal.FindByIdentity(context, username); return (user != null) ? true : false; } } i am unable to create object of PrincipalContext based on given arguments. i am getting this exception "{"The server could not be contacted."}" and inner exception states that "{"The LDAP server is unavailable."}" where as domain is running. i can ping to it and can also connect to this domain. any suggestion about these exceptions?

    Read the article

  • How can I check a user/password combination on an ActiveDirectory without putting the password in a String?

    - by Jean Hominal
    I want to check User/Password combination on a Windows domain. Right now I do it with the following code: bool Login(String username, String password) { var principalContext = new PrincipalContext(ContextType.Domain); principalContext.ValidateCredentials(username, password); } While it works, the thing that bugs me is that I have to put the password in a String in order to use that API; as I am using a SecureString to store the password everywhere else, I would really like to use some way of checking the username / password combination without having to pass the password as a managed System.String. What would be the best way of achieving that?

    Read the article

  • How to make an IDisposable object a class variable?

    - by Ben Aston
    I am working with Active Directory using C#. Instantiating the PrincipalContext object seems to be expensive, so I'd like to store one in a class variable. When using PrincipalContext as a local variable, I can use the convenient using syntax. When storing an IDisposable object in a static variable, how do I ensure the object is properly disposed of?

    Read the article

  • System.DirectoryServices.AccountManagement functions fail to probe some machines (but not others)

    - by JCCyC
    Both the working and failing targets are machines in the same domain. Code is down below. When I use it against some machines in my domain, I get a System.DirectoryServices.AccountManagement.PrincipalOperationException with a message: "While trying to retrieve the authorization groups, an error (1332) occurred." The error is thrown by GetAuthorizationGroups(). Note: The username I use to connect is a local admin to the machine in both cases. PrincipalContext ctx = new PrincipalContext(ContextType.Machine, machineName, domainname + "\\" + adminusername, pass); List<Principal> retList = new List<Principal>(); using (var user = UserPrincipal.FindByIdentity(ctx, probedusername)) { if (user != null) { PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups(); foreach (Principal group in groups) { retList.Add(group); } } }

    Read the article

  • How to get a list of groups in an Active Directory group

    - by Douglas Anderson
    I'm trying to get a list of the groups that are in an AD group using .NET. As an example, I have a group called TestGroup and inside that group I have the group DomainAdministrators. Using the code below I can get all of the users including those from the DomainAdministrators group but not the group itself. PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DomainName"); GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, "TestGroup"); ArrayList members = new ArrayList(); if (grp != null) { foreach (Principal p in grp.GetMembers(true)) { members.Add(p.Name) } } grp.Dispose(); ctx.Dispose(); Instead of GetMembers I've tried GetGroups but that doesn't return anything. How can I return the groups in the group?

    Read the article

  • Check if user exists in Active Directory

    - by K.R.
    Hello, I need to check if an user exists in AD and if so, retrieve some user information. I have been able to do this as shown below. But, it is very slow. Is there any way to do this faster? Thanks! using System; using System.DirectoryServices; using System.DirectoryServices.AccountManagement; namespace ConsoleApplication1 { class Program { static void Main() { Console.WriteLine("Enter AD account name..."); string strADLoginName = Console.ReadLine(); using(PrincipalContext context = new PrincipalContext(ContextType.Domain,"DEVMC")) { using (UserPrincipal user = UserPrincipal.FindByIdentity(context, strADLoginName)) { bool userExists = (user != null); if (userExists) { Console.WriteLine("User exists"); Console.WriteLine(user.EmailAddress); } else { Console.WriteLine("User doesn't exist"); } } } Console.ReadKey(); } } }

    Read the article

  • ValidateCredentials() returns FALSE on First Call but TRUE on Subsequent Calls

    - by Nick Gotch
    I'm using the following code to authenticate users on my web service: using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domain)) { return context.ValidateCredentials(userName, password); } The obstacle I'm running into is that the first call to ValidateCredentials() is returning false but subsequent calls return true. I placed a breakpoint at this line and in the Intermediate window I see the same results: first call returns false, second returns true, even though nothing was changed (by me) between calls. The 'domain' is String.Empty but I've also tried it with the actual domain name and get the same results. I'm not that versed in network administration so any help would be appreciated,

    Read the article

  • C# Active Directory Group Querying

    - by user1073912
    I am trying the code found here. I am getting the following compile time error: The name 'p' does not exist in the current context Here is my code...can someone help? Thanks. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.DirectoryServices; using System.DirectoryServices.AccountManagement; public static List<string> GetGroups() { using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain)) { using (p = Principal.FindByIdentity(ctx, "yourUserName")) { var groups = p.GetGroups(); using (groups) { foreach (Principal group in groups) { Console.WriteLine(group.SamAccountName + "-" + group.DisplayName); } } } } }

    Read the article

  • Changing a limited user account in XP fails

    - by javamonkey79
    I have the following: using System; using System.DirectoryServices.AccountManagement; public class ChangePassword { public static void Main() { PrincipalContext context = new PrincipalContext(ContextType.Machine); UserPrincipal user = UserPrincipal.FindByIdentity(context, "someLimitedAccount"); user.ChangePassword( "xxx", "zzz" ); } } This works just fine with administrator accounts, but seems to crash like so when I try to change limited accounts in XP: Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at ChangePassword.Main() Is what I am trying to do possible? If so, how? EDIT #1: I added the following: Console.WriteLine( "user: " + user ); Below this line: UserPrincipal user = UserPrincipal.FindByIdentity(context, "someLimitedAccount"); And I get this: user: It doesn't look like user is null when I print it, but then again I'm not really a .Net guy - I seem to remember this being expected behavior.

    Read the article

  • How to check whether a user belongs to an AD group and nested groups?

    - by elsharpo
    hi guys, I have an ASP.NET 3.5 application using Windows Authentication and implementing our own RoleProvider. Problem is we want to restrict access to a set of pages to a few thousand users and rathern than inputing all of those one by one we found out they belong to an AD group. The answer is simple if the common group we are checking membership against the particular user is a direct member of it but the problem I'm having is that if the group is a member of another group and then subsequently member of another group then my code always returns false. For example: Say we want to check whether User is a member of group E, but User is not a direct member of *E", she is a member of "A" which a member of "B" which indeed is a member of E, therefore User is a member of *E" One of the solutions we have is very slow, although it gives the correct answer using (var context = new PrincipalContext(ContextType.Domain)) { using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.Name, "DL-COOL-USERS")) { var users = group.GetMembers(true); // recursively enumerate return users.Any(a => a.Name == "userName"); } } The original solution and what I was trying to get to work, using .NET 3.5 System.DirectoryServices.AccountManagement and it does work when users are direct members of the group in question is as follows: public bool IsUserInGroup(string userName, string groupName) { var cxt = new PrincipalContext(ContextType.Domain, "DOMAIN"); var user = UserPrincipal.FindByIdentity(cxt, IdentityType.SamAccountName, userName); if (user == null) { return false; } var group = GroupPrincipal.FindByIdentity(cxt, groupName); if (group == null) { return false; } return user.IsMemberOf(group); } The bottom line is, we need to check for membership even though the groups are nested in many levels down. Thanks a lot!

    Read the article

  • Different approaches for finding users within Active Directory

    - by EvilDr
    I'm a newbie to AD programming, but after a couple of weeks of research have found the following three ways to search for users in Active Directory using the account name as the search parameter: Option 1 - FindByIdentity Dim ctx As New PrincipalContext(ContextType.Domain, Environment.MachineName) Dim u As UserPrincipal = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "MYDOMAIN\Administrator") If u Is Nothing Then Trace.Warn("No user found.") Else Trace.Warn("Name=" & u.Name) Trace.Warn("DisplayName=" & u.DisplayName) Trace.Warn("DistinguishedName=" & u.DistinguishedName) Trace.Warn("EmployeeId=" & u.EmployeeId) Trace.Warn("EmailAddress=" & u.EmailAddress) End If Option 2 - DirectorySearcher Dim connPath As String = "LDAP://" & Environment.MachineName Dim de As New DirectoryEntry(connPath) Dim ds As New DirectorySearcher(de) ds.Filter = String.Format("(&(objectClass=user)(anr={0}))", Split(User.Identity.Name, "\")(1)) ds.PropertiesToLoad.Add("name") ds.PropertiesToLoad.Add("displayName") ds.PropertiesToLoad.Add("distinguishedName") ds.PropertiesToLoad.Add("employeeId") ds.PropertiesToLoad.Add("mail") Dim src As SearchResult = ds.FindOne() If src Is Nothing Then Trace.Warn("No user found.") Else For Each propertyKey As String In src.Properties.PropertyNames Dim valueCollection As ResultPropertyValueCollection = src.Properties(propertyKey) For Each propertyValue As Object In valueCollection Trace.Warn(propertyKey & "=" & propertyValue.ToString) Next Next End If Option 3 - PrincipalSearcher Dim ctx2 As New PrincipalContext(ContextType.Domain, Environment.MachineName) Dim sp As New UserPrincipal(ctx2) sp.SamAccountName = "MYDOMAIN\Administrator" Dim s As New PrincipalSearcher s.QueryFilter = sp Dim p2 As UserPrincipal = s.FindOne() If p2 Is Nothing Then Trace.Warn("No user found.") Else Trace.Warn(p2.Name) Trace.Warn(p2.DisplayName) Trace.Warn(p2.DistinguishedName) Trace.Warn(p2.EmployeeId) Trace.Warn(p2.EmailAddress) End If All three of these methods return the same results, but I was wondering if any particular method is better or worse than the others? Option 1 or 3 seem to be the best as they provide strongly-typed property names, but I might be wrong? My overall objective is to find a single user within AD based on the user principal value passed via the web browser when using Windows Authentication on a site (e.g. "MYDOMAIN\MyUserAccountName")

    Read the article

  • Getting the full-name of the current user, returns an empty string (C#/C++)

    - by Nir
    I try to get the full-name of the current log-in user (Fullname, not username). The following code C#, C++ works fine but on XP computers not connected to the Net, I get empty string as result if I run it ~20 minutes after login (It runs OK whithin the first ~20 minutes after login) A Win32 API (GetUserNameEx) is used rather that PrincipalContext since it PrincipalContext may takes up to 15 seconds when working offline. Any Help why am I getting an empty string as result though a user full name is specified??? - C# Code public static string CurrentUserFullName { get { const int EXTENDED_NAME_FORMAT_NAME_DISPLAY = 3; StringBuilder userName = new StringBuilder(256); uint length = (uint) userName.Capacity; string ret; if (GetUserNameEx(EXTENDED_NAME_FORMAT_NAME_DISPLAY, userName, ref length)) { ret = userName.ToString(); } else { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception("GetUserNameEx Failed. Error code - " + errorCode); } return ret; } } [DllImport("Secur32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool GetUserNameEx(int nameFormat, StringBuilder lpNameBuffer, ref uint lpnSize); - Code in C++ #include "stdafx.h" #include <windows.h> #define SECURITY_WIN32 #include <Security.h> #pragma comment( lib, "Secur32.lib" ) int _tmain(int argc, _TCHAR* argv[]) { char szName[100]; ULONG nChars = sizeof( szName ); if ( GetUserNameEx( NameDisplay, szName, &nChars ) ) { printf( "Name: %s\n", szName); } else { printf( "Failed to GetUserNameEx\n" ); printf( "%d\n", GetLastError() ); } return 0; }

    Read the article

  • User to be validated against nested security groups in Windows.

    - by user412272
    Hi, This is my first post here and after much looking around I have come here with my question. Will really appreciate a fast response. I am faced with a problem to validate user credentials of the currently logged on user against a group in Windows. The user membership to a group can be through other groups also ie nested membership. Eg. User U is a part of group G1. Group G1 is a part of another group G2. The requirement is that when the user is validated against group G2, the validations should succeed. The user can be a local or AD user but the group will always be a local group ( or domain local group if created directly on a DC). I have tried using WindowsPrincipal.IsInRole() method, but it seems to be checking only for direct membership to a group. I also tried UserPrincipal.GetAuthorizationGroups() for the current user, but it also doesnt seem to be doing recursive search. I am posting a code snippet of the working code below, but this code is taking much more than acceptable time. bool CheckUserPermissions(string groupName) { WindowsIdentity currentUserIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); bool found = false; PrincipalContext context= new PrincipalContext(ContextType.Machine); GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.Name, groupName); if (group!= null) { foreach (Principal p in group.GetMembers(true)) { if (p.Sid == currentUserIdentity.User) { found = true; break; } } group.Dispose(); } return found; }

    Read the article

  • AD Password About to Expire check problem with ASP.Net

    - by Vince
    Hello everyone, I am trying to write some code to check the AD password age during a user login and notify them of the 15 remaining days. I am using the ASP.Net code that I found on the Microsoft MSDN site and I managed to add a function that checks the if the account is set to change password at next login. The login and the change password at next login works great but I am having some problems with the check for the password age. This is the VB.Net code for the DLL file: Imports System Imports System.Text Imports System.Collections Imports System.DirectoryServices Imports System.DirectoryServices.AccountManagement Imports System.Reflection 'Needed by the Password Expiration Class Only -Vince Namespace FormsAuth Public Class LdapAuthentication Dim _path As String Dim _filterAttribute As String 'Code added for the password expiration added by Vince Private _domain As DirectoryEntry Private _passwordAge As TimeSpan = TimeSpan.MinValue Const UF_DONT_EXPIRE_PASSWD As Integer = &H10000 'Function added by Vince Public Sub New() Dim root As New DirectoryEntry("LDAP://rootDSE") root.AuthenticationType = AuthenticationTypes.Secure _domain = New DirectoryEntry("LDAP://" & root.Properties("defaultNamingContext")(0).ToString()) _domain.AuthenticationType = AuthenticationTypes.Secure End Sub 'Function added by Vince Public ReadOnly Property PasswordAge() As TimeSpan Get If _passwordAge = TimeSpan.MinValue Then Dim ldate As Long = LongFromLargeInteger(_domain.Properties("maxPwdAge")(0)) _passwordAge = TimeSpan.FromTicks(ldate) End If Return _passwordAge End Get End Property Public Sub New(ByVal path As String) _path = path End Sub 'Function added by Vince Public Function DoesUserHaveToChangePassword(ByVal userName As String) As Boolean Dim ctx As PrincipalContext = New PrincipalContext(System.DirectoryServices.AccountManagement.ContextType.Domain) Dim up = UserPrincipal.FindByIdentity(ctx, userName) Return (Not up.LastPasswordSet.HasValue) 'returns true if last password set has no value. End Function Public Function IsAuthenticated(ByVal domain As String, ByVal username As String, ByVal pwd As String) As Boolean Dim domainAndUsername As String = domain & "\" & username Dim entry As DirectoryEntry = New DirectoryEntry(_path, domainAndUsername, pwd) Try 'Bind to the native AdsObject to force authentication. Dim obj As Object = entry.NativeObject Dim search As DirectorySearcher = New DirectorySearcher(entry) search.Filter = "(SAMAccountName=" & username & ")" search.PropertiesToLoad.Add("cn") Dim result As SearchResult = search.FindOne() If (result Is Nothing) Then Return False End If 'Update the new path to the user in the directory. _path = result.Path _filterAttribute = CType(result.Properties("cn")(0), String) Catch ex As Exception Throw New Exception("Error authenticating user. " & ex.Message) End Try Return True End Function Public Function GetGroups() As String Dim search As DirectorySearcher = New DirectorySearcher(_path) search.Filter = "(cn=" & _filterAttribute & ")" search.PropertiesToLoad.Add("memberOf") Dim groupNames As StringBuilder = New StringBuilder() Try Dim result As SearchResult = search.FindOne() Dim propertyCount As Integer = result.Properties("memberOf").Count Dim dn As String Dim equalsIndex, commaIndex Dim propertyCounter As Integer For propertyCounter = 0 To propertyCount - 1 dn = CType(result.Properties("memberOf")(propertyCounter), String) equalsIndex = dn.IndexOf("=", 1) commaIndex = dn.IndexOf(",", 1) If (equalsIndex = -1) Then Return Nothing End If groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1)) groupNames.Append("|") Next Catch ex As Exception Throw New Exception("Error obtaining group names. " & ex.Message) End Try Return groupNames.ToString() End Function 'Function added by Vince Public Function WhenExpires(ByVal username As String) As TimeSpan Dim ds As New DirectorySearcher(_domain) ds.Filter = [String].Format("(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))", username) Dim sr As SearchResult = FindOne(ds) Dim user As DirectoryEntry = sr.GetDirectoryEntry() Dim flags As Integer = CInt(user.Properties("userAccountControl").Value) If Convert.ToBoolean(flags And UF_DONT_EXPIRE_PASSWD) Then 'password never expires Return TimeSpan.MaxValue End If 'get when they last set their password Dim pwdLastSet As DateTime = DateTime.FromFileTime(LongFromLargeInteger(user.Properties("pwdLastSet").Value)) ' return pwdLastSet.Add(PasswordAge).Subtract(DateTime.Now); If pwdLastSet.Subtract(PasswordAge).CompareTo(DateTime.Now) > 0 Then Return pwdLastSet.Subtract(PasswordAge).Subtract(DateTime.Now) Else Return TimeSpan.MinValue 'already expired End If End Function 'Function added by Vince Private Function LongFromLargeInteger(ByVal largeInteger As Object) As Long Dim type As System.Type = largeInteger.[GetType]() Dim highPart As Integer = CInt(type.InvokeMember("HighPart", BindingFlags.GetProperty, Nothing, largeInteger, Nothing)) Dim lowPart As Integer = CInt(type.InvokeMember("LowPart", BindingFlags.GetProperty, Nothing, largeInteger, Nothing)) Return CLng(highPart) << 32 Or CUInt(lowPart) End Function 'Function added by Vince Private Function FindOne(ByVal searcher As DirectorySearcher) As SearchResult Dim sr As SearchResult = Nothing Dim src As SearchResultCollection = searcher.FindAll() If src.Count > 0 Then sr = src(0) End If src.Dispose() Return sr End Function End Class End Namespace And this is the Login.aspx page: sub Login_Click(sender as object,e as EventArgs) Dim adPath As String = "LDAP://DC=xxx,DC=com" 'Path to your LDAP directory server Dim adAuth As LdapAuthentication = New LdapAuthentication(adPath) Try If (True = adAuth.DoesUserHaveToChangePassword(txtUsername.Text)) Then Response.Redirect("passchange.htm") ElseIf (True = adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text)) Then Dim groups As String = adAuth.GetGroups() 'Create the ticket, and add the groups. Dim isCookiePersistent As Boolean = chkPersist.Checked Dim authTicket As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _ txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups) 'Encrypt the ticket. Dim encryptedTicket As String = FormsAuthentication.Encrypt(authTicket) 'Create a cookie, and then add the encrypted ticket to the cookie as data. Dim authCookie As HttpCookie = New HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) If (isCookiePersistent = True) Then authCookie.Expires = authTicket.Expiration End If 'Add the cookie to the outgoing cookies collection. Response.Cookies.Add(authCookie) 'Retrieve the password life Dim t As TimeSpan = adAuth.WhenExpires(txtUsername.Text) 'You can redirect now. If (passAge.Days = 90) Then errorLabel.Text = "Your password will expire in " & DateTime.Now.Subtract(t) 'errorLabel.Text = "This is" 'System.Threading.Thread.Sleep(5000) Response.Redirect("http://somepage.aspx") Else Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, False)) End If Else errorLabel.Text = "Authentication did not succeed. Check user name and password." End If Catch ex As Exception errorLabel.Text = "Error authenticating. " & ex.Message End Try End Sub ` Every time I have this Dim t As TimeSpan = adAuth.WhenExpires(txtUsername.Text) enabled, I receive "Arithmetic operation resulted in an overflow." during the login and won't continue. What am I doing wrong? How can I correct this? Please help!! Thank you very much for any help in advance. Vince

    Read the article

  • List local administrators with System.DirectoryServices.AccountManagement doesn't retrieve domain us

    - by yajohn
    I'm trying to remotely list members of the local Administrators group. The following code returns only local accounts which are members of the admin group - no domain groups or individual accounts are returned at all (BLAH\Domain Admins or BLAH\yajohn, for instance). Anyone have an idea? Public Function listLocalAdmins(ByVal machinename As String, ByVal creduname As String, ByVal credpass As String) As String Try Dim mctx As New PrincipalContext(ContextType.Machine, machinename, creduname, credpass) Dim lcladmins As GroupPrincipal = GroupPrincipal.FindByIdentity(mctx, IdentityType.Name, "Administrators") Dim pc As PrincipalCollection = lcladmins.Members Dim r As New StringBuilder For Each p As Principal In pc r.Append("Name:->" & p.Name.ToString & vbCrLf) Next Return r.ToString Catch ex As Exception Return ex.Message End Try End Function Thanks for any feedback.

    Read the article

  • Active Directory Group Members Issue

    - by kombsh
    Hi friends, I am using the below code to get the members from a group. private static List<string> GetGroupMembers(string groupName) { Tracer.LogEntrace(groupName); List<string> retVal = new List<string>(); GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity (new PrincipalContext(ContextType.Domain), IdentityType.SamAccountName, groupName); PrincipalSearchResult<Principal> principleSearchResult = groupPrincipal.GetMembers(true); if (principleSearchResult != null) { try { foreach (Principal item in principleSearchResult) { retVal.Add(item.DistinguishedName); } } catch (Exception ex) { Tracer.Log(ex.Message); } } else { //Do Nothing } Tracer.LogExit(retVal.Count); return retVal; } It works well for all groups but when its come to Users group i am getting the below error "An error (87) occurred while enumerating the groups. The group's SID could not be resolved." Can any one help regarding this one.

    Read the article

  • What is the easiest way to get the primary groupName from AD in C#?

    - by madhatter84gn
    I am currently using PrincipalContext and UserPrincipal to return the users primary groupid. How can I take this id and find the actual group name? Also I have code that works correctly to assign the user's primary group, but once I assign them to the group I can not delete them from Domain Users which is the default primary group prior to my change. I have called Save() before trying to remove the domain users group. My requirements state I must add the user to AD then assign their primary group and then remove them as a member of Domain Users.

    Read the article

  • Authenticating your windows domain users in the cloud

    - by cibrax
    Moving to the cloud can represent a big challenge for many organizations when it comes to reusing existing infrastructure. For applications that drive existing business processes in the organization, reusing IT assets like active directory represent good part of that challenge. For example, a new web mobile application that sales representatives can use for interacting with an existing CRM system in the organization. In the case of Windows Azure, the Access Control Service (ACS) already provides some integration with ADFS through WS-Federation. That means any organization can create a new trust relationship between the STS running in the ACS and the STS running in ADFS. As the following image illustrates, the ADFS running in the organization should be somehow exposed out of network boundaries to talk to the ACS. This is usually accomplish through an ADFS proxy running in a DMZ. This is the official story for authenticating existing domain users with the ACS.  Getting an ADFS up and running in the organization, which talks to a proxy and also trust the ACS could represent a painful experience. It basically requires  advance knowledge of ADSF and exhaustive testing to get everything right.  However, if you want to get an infrastructure ready for authenticating your domain users in the cloud in a matter of minutes, you will probably want to take a look at the sample I wrote for talking to an existing Active Directory using a regular WCF service through the Service Bus Relay Binding. You can use the WCF ability for self hosting the authentication service within a any program running in the domain (a Windows service typically). The service will not require opening any port as it is opening an outbound connection to the cloud through the Relay Service. In addition, the service will be protected from being invoked by any unauthorized party with the ACS, which will act as a firewall between any client and the service. In that way, we can get a very safe solution up and running almost immediately. To make the solution even more convenient, I implemented an STS in the cloud that internally invokes the service running on premises for authenticating the users. Any existing web application in the cloud can just establish a trust relationship with this STS, and authenticate the users via WS-Federation passive profile with regular http calls, which makes this very attractive for web mobile for example. This is how the WCF service running on premises looks like, [ServiceBehavior(Namespace = "http://agilesight.com/active_directory/agent")] public class ProxyService : IAuthenticationService { IUserFinder userFinder; IUserAuthenticator userAuthenticator;   public ProxyService() : this(new UserFinder(), new UserAuthenticator()) { }   public ProxyService(IUserFinder userFinder, IUserAuthenticator userAuthenticator) { this.userFinder = userFinder; this.userAuthenticator = userAuthenticator; }   public AuthenticationResponse Authenticate(AuthenticationRequest request) { if (userAuthenticator.Authenticate(request.Username, request.Password)) { return new AuthenticationResponse { Result = true, Attributes = this.userFinder.GetAttributes(request.Username) }; }   return new AuthenticationResponse { Result = false }; } } Two external dependencies are used by this service for authenticating users (IUserAuthenticator) and for retrieving user attributes from the user’s directory (IUserFinder). The UserAuthenticator implementation is just a wrapper around the LogonUser Win Api. The UserFinder implementation relies on Directory Services in .NET for searching the user attributes in an existing directory service like Active Directory or the local user store. public UserAttribute[] GetAttributes(string username) { var attributes = new List<UserAttribute>();   var identity = UserPrincipal.FindByIdentity(new PrincipalContext(this.contextType, this.server, this.container), IdentityType.SamAccountName, username); if (identity != null) { var groups = identity.GetGroups(); foreach(var group in groups) { attributes.Add(new UserAttribute { Name = "Group", Value = group.Name }); } if(!string.IsNullOrEmpty(identity.DisplayName)) attributes.Add(new UserAttribute { Name = "DisplayName", Value = identity.DisplayName }); if(!string.IsNullOrEmpty(identity.EmailAddress)) attributes.Add(new UserAttribute { Name = "EmailAddress", Value = identity.EmailAddress }); }   return attributes.ToArray(); } As you can see, the code is simple and uses all the existing infrastructure in Azure to simplify a problem that looks very complex at first glance with ADFS. All the source code for this sample is available to download (or change) in this GitHub repository, https://github.com/AgileSight/ActiveDirectoryForCloud

    Read the article

  • How to get foreignSecurityPrincipal from group. using DirectorySearcher

    - by kain64b
    What I tested with 0 results: string queryForeignSecurityPrincipal = "(&(objectClass=foreignSecurityPrincipal)(memberof:1.2.840.113556.1.4.1941:={0})(uSNChanged>={1})(uSNChanged<={2}))"; sidsForeign = GetUsersSidsByQuery(groupName, string.Format(queryForeignSecurityPrincipal, groupPrincipal.DistinguishedName, 0, 0)); public IList<SecurityIdentifier> GetUsersSidsByQuery(string groupName, string query) { List<SecurityIdentifier> results = new List<SecurityIdentifier>(); try{ using (var context = new PrincipalContext(ContextType.Domain, DomainName, User, Password)) { using (var groupPrincipal = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, groupName)) { DirectoryEntry directoryEntry = (DirectoryEntry)groupPrincipal.GetUnderlyingObject(); do { directoryEntry = directoryEntry.Parent; } while (directoryEntry.SchemaClassName != "domainDNS"); DirectorySearcher searcher = new DirectorySearcher(directoryEntry){ SearchScope=System.DirectoryServices.SearchScope.Subtree, Filter=query, PageSize=10000, SizeLimit = 15000 }; searcher.PropertiesToLoad.Add("objectSid"); searcher.PropertiesToLoad.Add("distinguishedname"); using (SearchResultCollection result = searcher.FindAll()) { foreach (var obj in result) { if (obj != null) { var valueProp = ((SearchResult)obj).Properties["objectSid"]; foreach (var atributeValue in valueProp) { SecurityIdentifier value = (new SecurityIdentifier((byte[])atributeValue, 0)); results.Add(value); } } } } } } } catch (Exception e) { WriteSystemError(e); } return results; } I tested it on usual users with query: "(&(objectClass=user)(memberof:1.2.840.113556.1.4.1941:={0})(uSNChanged>={1})(uSNChanged<={2}))" and it is work, I test with objectClass=* ... nothing help... But If I call groupPrincipal.GetMembers,I get all foreing user account from group. BUT groupPrincipal.GetMembers HAS MEMORY LEAK. Any Idea how to fix my query????

    Read the article

1