Solved

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

Posted on 2009-06-29
6
1,090 Views
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)?  

Thanks,
Slb2008
0
Comment
Question by:slb2008
  • 3
  • 3
6 Comments
 
LVL 20

Expert Comment

by:brwwiggins
Comment Utility
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
0
 

Author Comment

by:slb2008
Comment Utility

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
 
Domain : XXXXXX.XXX
                /Departments
                   /RecPlace
                       /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)
        Try
            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.
                Response.Cookies.Add(authCookie)
 
                'You can redirect now.
                Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, False))
            Else
                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)
 
            Try
                '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 + ")"
                search.PropertiesToLoad.Add("cn")
                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 + ")"
            search.PropertiesToLoad.Add("memberOf")
            Dim groupNames As New StringBuilder()
 
            Try
                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))
                    groupNames.Append("|")
                    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
    \Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
  <connectionStrings>
    <add name="ADConnectionString" connectionString=LDAP://DC=XXXXXX, DC=XXX providerName="System.DirectoryServices"/>
  </connectionStrings>
  <system.web>
 
   
    <authentication>
      <forms loginUrl="/ABC/login.aspx" timeout="480" />
    </authentication>
 
    <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">
      <assemblies>
        <add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>
    <pages>
      <namespaces>
        <clear/>
        <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"/>
      </namespaces>
      <controls>
      </controls>
    </pages>
    <!--
            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" />
        </customErrors>
        -->
    <!--<authorization>
      <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]"/>
            --><!--
    </authorization>-->
  <location allowOverride="true">
    <appSettings>
    </appSettings>
  </location>
</configuration>

Sincerely thanks  , slb2008
0
 
LVL 20

Expert Comment

by:brwwiggins
Comment Utility
In the authorization section, you need to add your group names to the allow roles entry in the format DOMAIN\groupname

http://msdn.microsoft.com/en-us/library/ms998358.aspx
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:slb2008
Comment Utility

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:
 
Domain : XXXXXX.XXX
                /Departments
                   /RecPlace
                       /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?
else  
// 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&
 

Thanks.
 
 
0
 
LVL 20

Accepted Solution

by:
brwwiggins earned 500 total points
Comment Utility
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.
0
 

Author Comment

by:slb2008
Comment Utility
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.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Shadow IT is coming out of the shadows as more businesses are choosing cloud-based applications. It is now a multi-cloud world for most organizations. Simultaneously, most businesses have yet to consolidate with one cloud provider or define an offic…
Restoring deleted objects in Active Directory has been a standard feature in Active Directory for many years, yet some admins may not know what is available.
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

772 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now