Active Directory and Restrictions Access to some ASP.NET Web Applications

Hi  Experts-Exchange,

I have an intranet page with different Asp.Net web applications links.  I created a code to authenticate Active Directory users, which is working well.  When the user logs in with username and password, if the user is authenticated by active directory goes in to the page, but there some web applications some users can't access because is restrict. I would like to know how to setup in the active directory users not having authorization to view the restricted web applications page(s)?  

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

brwwigginsIT ManagerCommented:
It's usually a function of the application to restrict access and not really store it in AD.

You can add roles to an application and if using AD authentication those equate to groups in AD. So if a user is not member of a certain group, then they cannot access the application if it is configured to use Roles
slb2008Author Commented:

Hi Brwwiggins,
Thanks for your quick response.
How to add roles to application using AD authentication to make equal to groups in AD?
I have VB.NET code and web configuration file, maybe you could review and help me how to add roles to application.  
In Active Directory I have this
                       /Security Groups
                               ABCWorkers  -    Paul, Victor, Lisa
                              RecPro -  John, Roy, Kevin
                              RecBos  Neil, Chase, Tim
If Kevin from the group RecPro login to the page which link is : http://abc/admin/Appl/Depart.aspx, that he has not rights to view that page, a message will display "You don't have any authorization to review this page, and redirects to login page and if Tim from the group RecBos login to the page which link is : http://abc/admin/Appl/Depart.aspx, that he has rights to view that page  so he will view the page, edit, change data.
Now the code:
This code if for authentication when Active Directory log in:
Protected Sub btnLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLogin.Click
        Dim adPath As String = "LDAP://DC=XXXXXX,DC=XXX"
        Dim adAuth As New ActiveDirectory.LDAPAuthentication(adPath)
            If 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 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 New HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
                If True = isCookiePersistent Then
                    authCookie.Expires = authTicket.Expiration
                End If
                'Add the cookie to the outgoing cookies collection.
                'You can redirect now.
                Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, False))
                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
        'Error authenticating. Error authenticating user. An invalid dn syntax has been specified
    End Sub
This is LDAPAuthentication.VB  file
Imports Microsoft.VisualBasic
Imports System
Imports System.Text
Imports System.Collections
Imports System.DirectoryServices
Namespace ActiveDirectory
    Public Class LDAPAuthentication
        Private _path As String
        Private _filterAttribute As String
        Public Sub New(ByVal path As String)
            _path = path
        End Sub
        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 New DirectoryEntry(_path, domainAndUsername, pwd)
                'Bind to the native AdsObject to force authentication.
                Dim obj As Object = entry.NativeObject
                Dim search As New DirectorySearcher(entry)
                search.Filter = "(CN=" + username + ")"
                                search.Filter = "(SAMAccountName=" + username + ")"
                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 = DirectCast(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 New DirectorySearcher(_path)
            search.Filter = "(cn=" + _filterAttribute + ")"
            Dim groupNames As New StringBuilder()
                Dim result As SearchResult = search.FindOne()
                Dim propertyCount As Integer = result.Properties("memberOf").Count
                Dim dn As String
                Dim equalsIndex As Integer, commaIndex As Integer
                Dim propertyCounter As Integer = 0
                While propertyCounter < propertyCount
                    dn = DirectCast(result.Properties("memberOf")(propertyCounter), String)
                    equalsIndex = dn.IndexOf("=", 1)
                    commaIndex = dn.IndexOf(",", 1)
                    If -1 = equalsIndex Then
                        Return Nothing
                    End If
                    groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1))
                    System.Math.Max(System.Threading.Interlocked.Increment(propertyCounter), propertyCounter - 1)
                End While
            Catch ex As Exception
                Throw New Exception("Error obtaining group names. " + ex.Message)
            End Try
            Return groupNames.ToString()
        End Function
    End Class
End Namespace
Both working well.
The web configuration file from application:
<?xml version="1.0"?>
    Note: As an alternative to hand editing this file you can use the
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    <add name="ADConnectionString" connectionString=LDAP://DC=XXXXXX, DC=XXX providerName="System.DirectoryServices"/>
      <forms loginUrl="/ABC/login.aspx" timeout="480" />
    <customErrors mode="Off"/>
    <!--  DATABASE ACCESS -->
    <identity impersonate="true"/>
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.
            Visual Basic options:
            Set strict="true" to disallow all data type conversions
            where data loss can occur.
            Set explicit="true" to force declaration of all variables.
    <compilation debug="true" strict="false" explicit="true">
        <add assembly="System.DirectoryServices, Version=, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add namespace="System"/>
        <add namespace="System.Collections"/>
        <add namespace="System.Collections.Specialized"/>
        <add namespace="System.Configuration"/>
        <add namespace="System.Text"/>
        <add namespace="System.Text.RegularExpressions"/>
        <add namespace="System.Web"/>
        <add namespace="System.Web.Caching"/>
        <add namespace="System.Web.SessionState"/>
        <add namespace="System.Web.Security"/>
        <add namespace="System.Web.Profile"/>
        <add namespace="System.Web.UI"/>
        <add namespace="System.Web.UI.WebControls"/>
        <add namespace="System.Web.UI.WebControls.WebParts"/>
        <add namespace="System.Web.UI.HtmlControls"/>
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.
        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
      <allow users="*"/>
      --><!-- necessary with forms authentication
        to force redirect to login page --><!--
      --><!--  <allow     users="[comma separated list of users]"
                             roles="[comma separated list of roles]"/>
                  <deny      users="[comma separated list of users]"
                             roles="[comma separated list of roles]"/>
  <location allowOverride="true">

Sincerely thanks  , slb2008
brwwigginsIT ManagerCommented:
In the authorization section, you need to add your group names to the allow roles entry in the format DOMAIN\groupname
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

slb2008Author Commented:

Do I need to setup the authorization section using ASP.NET websiteSite Administration Tool or I will add manually the domain\groupnames inside of web configuration.
I read the link you sent, but honestly this is first time I am doing this Authorization, Authentication, Roles.  Ive been doing a lot with SQL security but not roles, etc&  In this moment
I am little confused.  
As you can see the Active Directory structure:
                       /Security Groups
                               ABCWorkers  -    Paul, Victor, Lisa
                              RecPro -  John, Roy, Kevin
                              RecBos  Neil, Chase, Tim
Please review this if its correct according to the structure of AD, if this isnt correct please give some steps how to add them in authorization section and in vb code
<roleManager enabled=true/><authorization> <deny users="XXXXXX.XXX\Kevin" /> <allow roles=" XXXXXX.XXX\RecPro" /></authorization>
VB.NET Code:
 if(User.IsInRole(@"XXXXXX.XXX\RecPro\Kevin")) then
==Where do I put the url link so Kevin cannot view this page?
// Return unauthorized access error.
End if
So where do I put the line of code in web application aspx.vb
Please give me any sample How you could setup the authorization section from of Active Directory and I have URL pages for example:  

http://abc/admin/Appl/Depart.aspx  - Kevin is from RecPro and I dont want Kevin to view this link or page, but only Tim from RecBos
http://abc/admin/Appl/Image.aspx -  Kevin is from RecPro, AbcWorkers (Paul, Victor, Lisa) can view this page
http://abc/admin/Appl/Admin.aspx - John is from RecPro and can view this page but not Neil from RecBos&

brwwigginsIT ManagerCommented:
Personally, I think it will create a lot of work to try and use usernames to restrict access.

When you put the security in the web.config it is going to affect the entire site and not an individual page. You can have an additional web.config in sub folders to restrict access to that folder but it appears in your case you don't have it configured that way. It may be something to consider.

For the scenario you describe, you would put in the web.config allow roles=domain\recpro, domain\abc workers

Then in the page_load script of say the depart.aspx you would have to check if the username not = Tim then redirect to an error page. Then do the same for the admin page and so forth.

You will run into trouble if someone changes their username, need to add a person and so forth. You will have to modify the code each time.

I would suggest making the groups more granular and even consider using sub folders to control access to the app.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
slb2008Author Commented:
This is the right answer I was looking for.  Yes, I already setup web.config in sub folders to restrict access and some VB.NET code in the page_load *.aspx.vb applications.  It's working now.  Thanks for your help.  Your solution is accepted by me with 500 points.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.