pb wt Active Directory authentication

Last post 07-28-2009 5:18 AM by tng. 8 replies.

Sort Posts:

  • pb wt Active Directory authentication

    06-24-2009, 4:31 AM
    • Member
      3 point Member
    • tng
    • Member since 06-24-2009, 4:10 AM
    • Posts 26

    hi, i have pb wt Active Directory authentication:
    1) 1st try: Membership.GetUser return NULL
    2) 2nd try: DirectorySearcher search = new DirectorySearcher(_path);
    search.Filter = "(cn=" + _filterAttribute + ")";
    search.PropertiesToLoad.Add("memberOf");
    SearchResult result = search.FindOne(); go to catch exception

    S.O can help, pls? Here's my code:

    1st try :

    protected void LoginButton_Click(object sender, EventArgs e)
    {
    DirectoryEntry entry = new DirectoryEntry("LDAP://Media.local/DC=Media, DC=local", "media\\tng", "****");
    object connect = entry.NativeObject;
    DirectorySearcher search = new DirectorySearcher(entry);
    search.Filter = "(&(objectCategory=user)(SAMAccountName=*))";
    search.PropertiesToLoad.Add("cn");
    foreach (SearchResult result in search.FindAll())
    {
    DirectoryEntry dirEntry = result.GetDirectoryEntry();
    string login = (dirEntry.Properties["SAMAccountName"].Value != null) ? dirEntry.Properties["SAMAccountName"].Value.ToString() : String.Empty;
    string name = (dirEntry.Properties["sn"].Value != null) ? dirEntry.Properties["sn"].Value.ToString() : String.Empty;
    string surname = (dirEntry.Properties["givenName"].Value != null) ? dirEntry.Properties["givenName"].Value.ToString() : String.Empty;
    string tel = (dirEntry.Properties["TelephoneNumber"].Value != null) ? dirEntry.Properties["TelephoneNumber"].Value.ToString() : String.Empty;
    string email = (dirEntry.Properties["mail"].Value != null) ? dirEntry.Properties["mail"].Value.ToString() : String.Empty;
    string path = result.Path;
    string filterAttribute = (String)result.Properties["cn"][0];
    if (String.Compare(login, 0, "tng", 0, 3, true) == 0)
    {
    lErreur.Text = " login=" + login + " name=" + name + " surname=" + surname + " tel=" + tel + " email=" + email;
    if (Request.LogonUserIdentity.IsAuthenticated)
    lErreur.Text += " Request.LogonUserIdentity.IsAuthenticated=" + Request.LogonUserIdentity.Name;

    lErreur.Text += " User.Identity.IsAuthenticated=" + User.Identity.IsAuthenticated;
    // the debug skips the if case. In the label: login=TNG name=NGO surname=Thanh tel=01 00 00 00 00 email=thanh.ngo@media.com User.Identity.IsAuthenticated=False

    MembershipUser u = Membership.GetUser(Login1.UserName); //Login1.UserName=”tng”
    if (u == null) //u=null. WHY???
    {
    Login1.FailureText = "Invalid user name. Please check your user name and try again.";
    return;
    }
    if (Membership.ValidateUser(Login1.UserName.ToString(), Login1.Password.ToString()))
    {
    FormsAuthentication.RedirectFromLoginPage(Login1.UserName.ToString(), false);
    HttpContext.Current.Session["username"] = Login1.UserName.ToString();
    Response.Redirect("Welcome.aspx",false);
    }
    else
    Login1.FailureText = "Invalid password. Please check your password and try again.";
    break;
    }
    }
    }

    2nd try: I clear all & try the method proposed by msdn:

    public partial class Identification : System.Web.UI.Page
    {
    private string _path;
    private string _filterAttribute;
    public Identification(string path)
    {
    _path = path;
    }
    public bool IsAuthenticated(string domain, string username, string pwd)
    {
    string domainAndUsername = domain + username;
    DirectoryEntry entry = new DirectoryEntry( _path, domainAndUsername, pwd);
    try
    {
    Object obj = entry.NativeObject;
    DirectorySearcher search = new DirectorySearcher(entry);
    search.Filter = "(SAMAccountName=" + username + ")";
    search.PropertiesToLoad.Add("cn");
    SearchResult result = search.FindOne();
    if(null == result)
    {
    return false;
    }
    _path = result.Path;
    _filterAttribute = (String)result.Properties["cn"][0];
    }
    catch (Exception ex)
    {
    throw new Exception("Error authenticating user. " + ex.Message);
    }
    return true;
    }
    public string GetGroups()
    {
    DirectorySearcher search = new DirectorySearcher(_path);
    search.Filter = "(cn=" + _filterAttribute + ")"; //search.filter=”Thanh NGO”
    search.PropertiesToLoad.Add("memberOf");
    StringBuilder groupNames = new StringBuilder();
    try
    {
    SearchResult result = search.FindOne(); //aller dans catch(exception ex). Pourquoi???
    int propertyCount = result.Properties["memberOf"].Count;
    String dn;
    int equalsIndex, commaIndex;
    for( int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
    {
    dn = (String)result.Properties["memberOf"][propertyCounter];
    equalsIndex = dn.IndexOf("=", 1);
    commaIndex = dn.IndexOf(",", 1);
    if (-1 == equalsIndex)
    {
    return null;
    }
    groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
    groupNames.Append("|");
    }
    }
    catch(Exception ex)
    {
    throw new Exception("Error obtaining group names. " + ex.Message);
    }
    return groupNames.ToString();
    }
    protected void LoginButton_Click(object sender, EventArgs e)
    {
    string adPath = "LDAP://Media.local/DC=Media,DC=local";
    Identification adAuth = new Identification(adPath);
    try
    {
    if (true == adAuth.IsAuthenticated("Media\\",
    Login1.UserName.ToString(),Login1.Password.ToString()))
    {
    string groups = adAuth.GetGroups(); //aller dans catch(exception ex).Regarde fct
    //GetGroups() en haut
    FormsAuthenticationTicket authTicket =
    new FormsAuthenticationTicket(1, Login1.UserName.ToString(),DateTime.Now, DateTime.Now.AddMinutes(60),false, groups);
    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
    HttpCookie authCookie = new Cookie(FormsAuthentication.FormsCookieName,
    encryptedTicket);
    Response.Cookies.Add(authCookie);
    Response.Redirect("Welcome.aspx",false)Response.Redirect("Welcome.aspx",false);
    }
    else
    {
    lErreur.Text =
    "Authentication failed, check username and password.";
    }
    }
    catch(Exception ex)
    {
    lErreur.Text = "Error authenticating. " + ex.Message;
    }
    }
    }

    here's my web.config for both try:

    <?xml version="1.0"?>
    <configuration>
    <connectionStrings>
    <add name="ADMedia" connectionString="LDAP://Media"/>
    </connectionStrings>
    <system.web>
    <authentication mode="Forms">
    <forms loginUrl="login.aspx" path="/" requireSSL="false"
    cookieless="UseDeviceProfile" enableCrossAppRedirects="false"
    protection="All" domain=http://Media name=".ASPXFORMSAUTH">
    </forms>
    </authentication>
    <membership defaultProvider="AspNetActiveDirectoryMembershipProvider" >
    <providers>
    <remove name="AspNetActiveDirectoryMembershipProvider"/>
    <add connectionStringName="ADMedia" connectionUsername="media\tng" connectionPassword="****" name="AspNetActiveDirectoryMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider,System.Web,version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"/>
    </providers>
    </membership>
    <roleManager enabled="true"/>
    <anonymousIdentification enabled="true"/>


    Média is a Outlook LDAP (wich is in another pc & linked to mine by intranet) where there's every information (name, surname, email, tel, group, @pc).
    I configured IIS like this : in directory security :
    - check Anonymous Connection
    - uncheck Authorise psw verification by IIS
    - check base authentification, default domain : Media, domain: Media.local
    - check window integreted authentification

    I can't connect to management of ASP.NET via SiteWeb menu in VisualStudio2008. Error: “Provider Management Could not establish a connection to the database. If you have not yet created the SQL Server database, exit the Web Site Administration tool, use the aspnet_regsql command-line utility to create and configure the database, and then return to this tool to set the provider.”

    I executed aspnet_regsql from the command line, nothing changed. What else I have to do? Thank you for your help

  • Re: pb wt Active Directory authentication

    06-24-2009, 5:20 AM
    • Contributor
      2,367 point Contributor
    • akhhttar
    • Member since 02-14-2007, 8:17 AM
    • Pakistan - Lahore
    • Posts 352

    Please see my latest article on the Windows Authentication using Form Authentication,

    http://www.codeproject.com/KB/aspnet/WinAuthusingFormAuth.aspx

    It is an easy way to authentication windows user.


    Thanks

    -Akhtar

    Lets resolve the problem together.

    Please remember to mark the appropriate replies as answer after your question is solved, thanks

    My Blog
  • Re: pb wt Active Directory authentication

    06-24-2009, 5:48 AM
    • Member
      3 point Member
    • tng
    • Member since 06-24-2009, 4:10 AM
    • Posts 26

    Thank you akhhttar, you saved me, i'm blocked since 2 days!

    Another question:  how to determine the FormsAuthentication.RedirectFromLoginPage for my users? I mean: when a user is authenticated (succesfully logged in), they will be redirected to a welcome page in which they can see links to other pages. According to their groups (of rights), they can see less or more links. How can I tell this "welcome" page to hide some links to some groups & show them to others? Thank you very much!

  • Re: pb wt Active Directory authentication

    06-24-2009, 6:31 AM
    • Contributor
      2,367 point Contributor
    • akhhttar
    • Member since 02-14-2007, 8:17 AM
    • Pakistan - Lahore
    • Posts 352

    FormsAuthentication.RedirectFromLoginPage() is used to redirect the user to the page that he actually requested. 

    if you always want to redirect the user to welcome page then you should  use FormsAuthentication.SetAuthCookie() method to genrate authentication token and then redirect the user to different welcome pages according to the users rights.


    Do you want to ask How to check user's rights? I mean eitehr s/he is part of particular windows group member or not?


    Thanks

    Muhammad Akhtar Shiekh







    Lets resolve the problem together.

    Please remember to mark the appropriate replies as answer after your question is solved, thanks

    My Blog
  • Re: pb wt Active Directory authentication

    06-24-2009, 6:59 AM
    • Member
      3 point Member
    • tng
    • Member since 06-24-2009, 4:10 AM
    • Posts 26

    No, I have for a simple example 3 users in 3 groups: Admin in Admin group, Employee in Emplyee group, Employer in Emplyer group

    from the login page, if the user is authenticated, he'll be redirected to a welcome page.

    In the welcome page, there will be only 3 links:

         <a href= "Admin management.aspx">Admin management</a>
     
         <a href="Employee management.aspx">Employee management</a>
      
         <a href="Employer management.aspx">Employer management</a>

    people having Employee rights (group Employee) can only see the link to Employee management page.

    peole having Employer rights (group Emplyer) can see both the link to Employee & Employer management pages.

    peole having Admin rights (group Admin) can see all the 3 links.

    What can I do in welcome page to express this intention?  Something like: if (User.Group=="Employee") {...} else if (User.Group=="Employee") {} else {}

  • Re: pb wt Active Directory authentication

    06-24-2009, 7:41 AM
    • Contributor
      2,367 point Contributor
    • akhhttar
    • Member since 02-14-2007, 8:17 AM
    • Pakistan - Lahore
    • Posts 352


    HI,

    You need to query to Active directory to find out that logged in user is in membership of particular group or not?

    Otherwise you can use Active Directory Mebmbership Provider which can do that task for you by using User.IsInRole() method.


    e.g

     if ( User.IsInRole("Admin") )

    {

    Response.Redirect("Admin.aspx");

    }

    else if (User.IsInRole("Employee"))

    {

    Response.Redirect("Employee.aspx");

    }


    To learn about Active Directory Membership Provider, please see http://msdn.microsoft.com/en-us/library/system.web.security.activedirectorymembershipprovider.aspx


    Thanks

    -Muhammad Akhtar Shiekh


    Lets resolve the problem together.

    Please remember to mark the appropriate replies as answer after your question is solved, thanks

    My Blog
  • Re: pb wt Active Directory authentication

    06-24-2009, 9:03 AM
    • Member
      3 point Member
    • tng
    • Member since 06-24-2009, 4:10 AM
    • Posts 26

    hello,


    I read the MSDN help but I didn't understand where to put this code in my prgr

    [DirectoryServicesPermissionAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)]
    [AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [DirectoryServicesPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
    [AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    public class ActiveDirectoryMembershipProvider : MembershipProvider

    My web.config is exactly what's shown in MSDN. In my login.aspx.cs there's now :
    bool result = LogonUser(userName, domainName, Login1.Password.ToString(), 2, 0, ref token);
            if (result)
            {
                if (string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
                {
                    if (User.IsInRole("Admin"))
                    {
                        Response.Redirect("WelcomeToAdmin.aspx");
                    }
                    else
                    {
                        Response.Redirect("WelcomeToAll.aspx");
                    }
                }
    }

    1) The pb is User is empty. I saw that it's a System.Web.Security.RolePrincipal object, but where is it created?

    2) Instead of using 2 pages WelcomeToAdmin.aspx & WelcomeToAll.aspx with nearly the same content, I'd like to only have one welcome.aspx page:
                if (string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
                {
                        Response.Redirect("Welcome.aspx");
    }
    And in welcome.aspx:
    if (...) { //asp code
    <a href= "Employee.aspx">Gestion des commandes</a> <!--html code-->
    } else { //asp code
    <a href= "Employee.aspx">Gestion des commandes</a> <!--html code-->
    <a href= "Admin.aspx">Gestion des commandes</a>
    }

    3) Is it possible to mix the asp & html code like shown above? (like <script> //code in javascript </script>)

    Does anyone have the answer? Thank you!!




  • Re: pb wt Active Directory authentication

    06-24-2009, 12:20 PM
    Answer
    • Contributor
      2,367 point Contributor
    • akhhttar
    • Member since 02-14-2007, 8:17 AM
    • Pakistan - Lahore
    • Posts 352

    Hi,


    You are doing one major mistake, You need to understand that ActiveDirectoryMembership Provider and LogonUser() ( The way i wrote in the article) both are alternatives, you can't use both togather.

    Please try http://msdn.microsoft.com/en-us/library/ms998360.aspx to get more understand and How to use ActiverDirectoryMembership Provider.

    However there are the answers of your questions,

    1. User property would be populated after genrating authentication token. Authentication token can be genrated by FormsAuthentication.RedirectFromLoginPage() OR FormsAuthentication.SetAuthCookie() method, as i discussed in my article.

    2. Yes, you can use single welcome page. It all related to your business logic.

    3. Yes you can use asp server tags in html markup. like following

    <% if (...) %> 
    <a href= "Employee.aspx">Gestion des commandes</a>
    <% else %>
    <a href= "Employee.aspx">Gestion des commandes</a>


    Thanks
    Muhammad Akhtar Shiekh




    Lets resolve the problem together.

    Please remember to mark the appropriate replies as answer after your question is solved, thanks

    My Blog
  • Re: pb wt Active Directory authentication

    07-28-2009, 5:18 AM
    • Member
      3 point Member
    • tng
    • Member since 06-24-2009, 4:10 AM
    • Posts 26

    Hello,


    In fact, my authenticate with LDAP works well (not what I thought), just because after the authentication I made another control to find in which group the login belongs to before redirect it to another page & this control doesn't work. Thanks for your help!

Page 1 of 1 (9 items)