Reputation: 4811
Currently, I am validating the credentials of an Active Directory user with the help of this code:
string _groups = "";
bool _isAuthSuccess=true;
List<string> user_groups = new List<string>();
try
{
using (PrincipalContext _loginContext = new PrincipalContext(ContextType.Domain, "domainname"))
{
_message += "calling ValidateCredentials";
_isAuthSuccess = _loginContext.ValidateCredentials(model.Email, model.Password);
if(_isAuthSuccess)
{
_message += "calling FindByIdentity";
var user = UserPrincipal.FindByIdentity(_loginContext, model.Email);
if (user != null)
{
// get the user's groups
_message += "calling GetAuthorizationGroups";
var groups = user.GetAuthorizationGroups();
foreach (GroupPrincipal group in groups)
{
// save those groups to session for further processing after login
if ((bool)group.IsSecurityGroup)
{
user_groups.Add(group.Name);
}
}
}
_groups = string.Join(",", user_groups);
}
else
{
_message += "_isAuthSuccess is false";
}
}
}
catch (PrincipalServerDownException)
{
_message += "Error at logon validatyion as server is down ";
}
catch(Exception ex)
{
_message += "Exception : "+ex.Message;
}
The bool flag is returning the status the user credentials are valid or not. Now i wanted to fetch the list of Active Directory UserGroups the user is a member of. I found that the method GetAuthorizationGroups
will return the list of user groups. But I am struggling to relate these 2 methods as there is no way to call _loginCOntext.GetAuthorizationGroups()
So how can efficiently handle these 2 cases together
Upvotes: 1
Views: 846
Reputation: 40928
The GetAuthorizationGroups()
method can only be called on a UserPricipal
, so you need to get one for the user. That's easy to do with the UserPrincipal.FindByIdentity
method (while reusing the _loginContext
object you already have):
var user = UserPrincipal.FindByIdentity(_loginContext, user_name);
var groups = user.GetAuthorizationGroups();
Update: To avoid the "Multiple connections" error, try using different instances of PrincipalContext
for each operation. At the end of the using
, it should disconnect the connection with the server and allow you to start a new one with different credentials without problem.
using (PrincipalContext _loginContext = new PrincipalContext(ContextType.Domain, "domainname"))
{
_message += "calling ValidateCredentials";
_isAuthSuccess = _loginContext.ValidateCredentials(model.Email, model.Password);
}
using (PrincipalContext _loginContext = new PrincipalContext(ContextType.Domain, "domainname", "username", "password"))
{
if(_isAuthSuccess)
{
...
}
else
{
_message += "_isAuthSuccess is false";
}
}
Upvotes: 2