Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


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

Posted on 2009-06-29
Medium Priority
Last Modified: 2013-12-24
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)?  

Question by:slb2008
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
LVL 20

Expert Comment

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

You can add roles to an asp.net 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

Author Comment

ID: 24740753

Hi Brwwiggins,
Thanks for your quick response.
How to add roles to asp.net 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 asp.net 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 asp.net 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
LVL 20

Expert Comment

ID: 24744925
In the authorization section, you need to add your group names to the allow roles entry in the format DOMAIN\groupname

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.


Author Comment

ID: 24746614

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 Asp.net 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&

LVL 20

Accepted Solution

brwwiggins earned 1500 total points
ID: 24755349
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.

Author Comment

ID: 24764618
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.

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A bad practice commonly found during an account life cycle is to set its password to an initial, insecure password. The Password Reset Tool was developed to make the password reset process easier and more secure.
One of the most important things in an application is the query performance. This article intends to give you good tips to improve the performance of your queries.
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.
Suggested Courses

604 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question