I had this issue for about a week ago. I managed making all the Active directory users to login to the website but now I want to restrict it to a particular group only lets say "Group1". Actually, I tried to use the following in web.config but it always asks fro credentials and even if I supply the valid users, it didn't accept it.
<authentication mode="Windows" />
<authorization>
<allow users="DomainName\Group1" />
<deny users="*" />
</authorization>
</system.web>
I tried most of the solutions suggested online like:
- Enabling windows authentication in both
IISand web site - Disable anonymous authentication
- if I changed the deny to
?, it will again enable all users to login without restricting to member of group1
the C# code
string dominName = string.Empty;
string adPath = string.Empty;
string userName = TextBox1.Text.Trim().ToUpper();
string strError = string.Empty;
try
{
foreach (string key in ConfigurationSettings.AppSettings.Keys)
{
dominName = key.Contains("DirectoryDomain") ? ConfigurationSettings.AppSettings[key] : dominName;
adPath = key.Contains("DirectoryPath") ? ConfigurationSettings.AppSettings[key] : adPath;
if (!String.IsNullOrEmpty(dominName) && !String.IsNullOrEmpty(adPath))
{
if (true == AuthenticateUser(dominName, userName, TextBox2.Text, adPath, out strError))
{
Response.Redirect("default.aspx");// Authenticated user redirects to default.aspx
}
dominName = string.Empty;
adPath = string.Empty;
if (String.IsNullOrEmpty(strError)) break;
}
}
if (!string.IsNullOrEmpty(strError))
{
Label3.Visible = true;
Label3.Text = "Wrong username or password";
}
}
catch
{
}
finally
{
}
}
public bool AuthenticateUser(string domain, string username, string password, string LdapPath, out string Errmsg)
{
Errmsg = "";
string domainAndUsername = domain + @"\" + username;
DirectoryEntry entry = new DirectoryEntry(LdapPath, domainAndUsername, password);
try
{
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.Filter = "(Group1=" + username + ")";
search.PropertiesToLoad.Add("memberOf");
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
// Update the new path to the user in the directory
LdapPath = result.Path;
string _filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
Errmsg = ex.Message;
return false;
throw new Exception("Error authenticating user." + ex.Message);
}
return true;
}
Hope to help me to solve this issue.