Role Based Windows Authentication

Last post 04-15-2008 8:01 AM by Shodan240z. 6 replies.

Sort Posts:

  • Role Based Windows Authentication

    04-10-2008, 9:41 AM
    • Member
      6 point Member
    • pabs1983
    • Member since 12-03-2006, 9:44 PM
    • Posts 25

    Hi, i am hoping that this is only a quicky. I have developed an intranet system for my department at work, we are using windows authentication. On my home page i have a contents menu, on this menu, i am wanting to limit what certain users see. I know that using 'forms' auth that i can use the loginview control and set roles up on there. 

     

    is it possible to set the loginview for just users OR define 2 users as admins in the web.config file? 

     

    Thanks in advance 

    pabs1983
  • Re: Role Based Windows Authentication

    04-10-2008, 9:48 AM
    • Contributor
      2,772 point Contributor
    • thirumaran007
    • Member since 03-14-2007, 5:39 AM
    • India
    • Posts 571

    Hi friend,
    use this code...

    Sub WindowsAuthentication_Authenticate(ByVal sender As Object, ByVal e As WindowsAuthenticationEventArgs)
        Dim roleStrng() As String = GetUserRoles()
        e.User = New GenericPrincipal(e.Identity, roleStrng)
    End Sub

    Private Function GetUserRoles() As String()
        Dim myDomain As AppDomain = Thread.GetDomain()
        myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
        Dim al As New ArrayList

        Dim myPrincipal As WindowsPrincipal = CType(Thread.CurrentPrincipal, WindowsPrincipal)
        Dim wbirFields As Array = [Enum].GetValues(GetType(WindowsBuiltInRole))
        Dim roleName As Object

        For Each roleName In wbirFields
            Try
                If myPrincipal.IsInRole(CType(roleName, WindowsBuiltInRole)) Then
                    al.Add(roleName.ToString())
                End If
            Catch

            End Try
        Next roleName

        Return CType(al.ToArray(GetType(String)), String())
    End Function

    With Friendly,
    Thirumaran

    Please remember to click "Mark as Answer" on this post if it helped you
  • Re: Role Based Windows Authentication

    04-10-2008, 9:54 AM
    • Member
      6 point Member
    • pabs1983
    • Member since 12-03-2006, 9:44 PM
    • Posts 25

    Is that using Windows based roles? Unfortunately, the 'admin' roles i am trying to use are not network admins. They are standard users on windows, but require to access other pages on the intranet.
     

    pabs1983
  • Re: Role Based Windows Authentication

    04-11-2008, 12:13 AM
    • Participant
      1,738 point Participant
    • CharlesF
    • Member since 04-10-2006, 2:54 PM
    • Everett, WA
    • Posts 326

    Sounds like what you need is to use a sitemap provider for your menu and have security trimming enabled. 

    This should get you started in the right direction...

    http://msdn2.microsoft.com/en-us/library/system.web.sitemapprovider.aspx

    http://msdn2.microsoft.com/en-us/library/system.web.xmlsitemapprovider.aspx

    http://msdn2.microsoft.com/en-us/library/ms227425.aspx

     

    Here's my design, if you're interested (not sure this is the best way or not, I'm self-taught): 

    First, I create custom Roles and manage them in my database. Then I allow roles access to directories and files in my application via the web.config, like this...

      <location path="roles.aspx">
        <system.web>
          <authorization>
            <allow roles="ManageRoles"/>
            <deny users="*" />
          </authorization>
        </system.web>
      </location>
      
      <location path="groups.aspx">
        <system.web>
          <authorization>
            <allow roles="ManageGroups"/>
            <deny users="*" />
          </authorization>
        </system.web>
      </location>
    
      <location path="users.aspx">
        <system.web>
          <authorization>
            <allow roles="ManageUsers"/>
            <deny users="*" />
          </authorization>
        </system.web>
      </location>

    Note: You don't have to create custom roles, you can put in the Windows Group names like this...

      <location path="users.aspx">
        <system.web>
          <authorization>
            <allow roles="BUILTIN\Administrators"/>
            <deny users="*" />
          </authorization>
        </system.web>
      </location

    <location path="groups.aspx">
        <system.web>
          <authorization>
            <allow roles="mydomain\mygroupname"/>
            <deny users="*" />
          </authorization>
        </system.web>
      </location>

    If you choose to not use custom roles, then you may want to consider adding this to your web.config...

    <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider"/>

    The trick is getting those roles assigned to the current logged in windows user.

    To do this, I create a Global Application Class (global.asax) and within the Application_PostAuthenticateRequest() event I have code that does the work necessary to build an ArrayList of Roles that the user should be in.

    Once I have the ArrayList (named "UserRoles") populated with the names of the roles I want to assign to the current user, I create a GenericPrinciple and assign it to the Context.User and System.Threading.Thread.CurrentPrinciple, as shown below:

                    ' Convert ArrayList of Objects into an Array of Strings
                    ReDim aryRoles(UserRoles.Count)
                    UserRoles.CopyTo(aryRoles)

                    ' Assign new principle to the system security Context and Thread for THIS user
                    Context.User = New System.Security.Principal.GenericPrincipal(Context.User.Identity, aryRoles)
                    System.Threading.Thread.CurrentPrincipal = New System.Security.Principal.GenericPrincipal(Context.User.Identity, aryRoles)

     

    Note: I also make sure to put the windows groups the user is currently in, into that list or roles as well.

    Here's a way to get the names of the roles a user is in... (this is way faster than Active Directory)

            Dim sb As StringBuilder = New StringBuilder
            Dim WinId As IIdentity = User.Identity
            Dim userId As WindowsIdentity = DirectCast(WinId, WindowsIdentity)
            sb.Append("<br /><b>Windows Groups</b> for: " & userId.Name)
            Dim irefGroups As IdentityReferenceCollection = userId.Groups.Translate(GetType(NTAccount))
            Dim idRef As NTAccount
            For i As Integer = 0 To irefGroups.Count - 1
                idRef = irefGroups(i)
                sb.Append("<br />" & idRef.ToString)
            Next
            Label1.Text = sb.ToString()

     

    I know, my method is a little complex. But I do it because my intranet web applications are "products" that I sell to clients. They set up their sites and they are not all that technical. So I need to be able to provide them a web interface that they can use to authorize users easily either by the Windows User Account name (domain\user) or Windows Group name (domain\group). With thousands of possible users, Forms authentication was out of the question. (What a nightmare for a non-technical person to have to deal with). In my method, they can utilize pre-existing windows groups and be up and running quickly.

    Hope this helps.

    There are no stupid questions, only easy answers. However, the quality of assistance you receive (if any) is directly proportional to the quality of your request.

    p.s. Please remember to "mark as answer" all posts that answer your question.
  • Re: Role Based Windows Authentication

    04-11-2008, 3:41 AM
    • Member
      6 point Member
    • pabs1983
    • Member since 12-03-2006, 9:44 PM
    • Posts 25

    Not sure about using XML Sitemap's, dont think they would help in this situation.

     

    I am currently using JavaScript for my menu (see below). What i am wanting to do, is allow 2 users from the Domain in to an 'SiteAdmin' area.

     

    When i use the ASP:LOGINVIEW control, and create a ROLEGROUP i get a sql error (i'm assuming this is because i am using WINDOWS AUTH)

     

    So, is there a way to create the admin roles, or specify that only those 2 users can view that menu?

     

            <div id="navigation">
                <!--Links used to initiate the sub menus. Pass in the desired submenu index numbers (ie: 0, 1) -->
                <a onmouseover="showit(0)" style="cursor: pointer;">Daily Checks</a> |
                <a onmouseover="showit(1)" style="cursor: pointer;">Documentation</a> |
                <a onmouseover="showit(2)" style="cursor: pointer;">Forum</a> |
                <a onmouseover="showit(3)" style="cursor: pointer;">Site Admin</a>     //This is the sites admin area, and as such, needs to be viewed only by the SiteAdmins.
               
                <ilayer name="dep1" bgcolor="transparent">
                    <layer name="dep2">
                    </layer>
                </ilayer>
                <div id="describe" class="contents" onmouseover="clear_delayhide()" onmouseout="resetit(event)">
                </div>

    <script language="JavaScript" type="text/javascript">
    var submenu=new Array()

    //Set submenu contents. Expand as needed. For each content, make sure everything exists on ONE LINE. Otherwise, there will be JS errors.
     
    submenu[0]='<a href="">Page 1</a> | <a href="">Page 2</a>'

    submenu[1]='<a href="">Page 1</a> | <a href="">Page 2</a>'

    submenu[2]='<a href="">Page 1</a> | <a href="">Page 2</a>'

    submenu[3]='<a href="">Page 1</a> | <a href="">Page 2</a>'


    //Set delay before submenu disappears after mouse moves out of it (in milliseconds)
    var delay_hide=1500

    /////THE JAVASCRIPT FOLLOWS HERE AND WORKS FINE

    pabs1983
  • Re: Role Based Windows Authentication

    04-11-2008, 4:59 AM
    Answer
    • Participant
      1,738 point Participant
    • CharlesF
    • Member since 04-10-2006, 2:54 PM
    • Everett, WA
    • Posts 326

    I'm sorry. I thought you wanted to restrict menu options displayed to the user based on the user's permissions.

    Me personally, I use the Menu control (or a third party one) that allows me to use an xmlSiteMap as my data source for the control. And if I configure the SiteMapProvider to have security trimming enabled, then AUTOMATICALLY the menu items are removed that the user doesn't have access to.

    I don't have to code anything to make this work.

    All i have to do is define access in my web.config file like I demonstrated in my previous post.

    But hey, if you want to re-build a better mouse trap, don't let me stop you.

    Might I suggest though, in the future, when you post a JavaScript question to an ASP.Net board, you should expect an ASP.Net answer again, not a JavaScript answer.

    Just sayin'  Stick out tongue

    Good luck with your client-side JavaScript menu.  :::cough::: mousetrap :::cough:::  Big Smile

    There are no stupid questions, only easy answers. However, the quality of assistance you receive (if any) is directly proportional to the quality of your request.

    p.s. Please remember to "mark as answer" all posts that answer your question.
  • Re: Role Based Windows Authentication

    04-15-2008, 8:01 AM
    Answer
    • Member
      92 point Member
    • Shodan240z
    • Member since 04-03-2008, 3:58 PM
    • Posts 11

    pabs1983:

    Not sure about using XML Sitemap's, dont think they would help in this situation.

     

    I am currently using JavaScript for my menu (see below). What i am wanting to do, is allow 2 users from the Domain in to an 'SiteAdmin' area.

     

    When i use the ASP:LOGINVIEW control, and create a ROLEGROUP i get a sql error (i'm assuming this is because i am using WINDOWS AUTH)

     

    So, is there a way to create the admin roles, or specify that only those 2 users can view that menu?

     

            <div id="navigation">
                <!--Links used to initiate the sub menus. Pass in the desired submenu index numbers (ie: 0, 1) -->
                <a onmouseover="showit(0)" style="cursor: pointer;">Daily Checks</a> |
                <a onmouseover="showit(1)" style="cursor: pointer;">Documentation</a> |
                <a onmouseover="showit(2)" style="cursor: pointer;">Forum</a> |
                <a onmouseover="showit(3)" style="cursor: pointer;">Site Admin</a>     //This is the sites admin area, and as such, needs to be viewed only by the SiteAdmins.
               
                <ilayer name="dep1" bgcolor="transparent">
                    <layer name="dep2">
                    </layer>
                </ilayer>
                <div id="describe" class="contents" onmouseover="clear_delayhide()" onmouseout="resetit(event)">
                </div>

    <script language="JavaScript" type="text/javascript">
    var submenu=new Array()

    //Set submenu contents. Expand as needed. For each content, make sure everything exists on ONE LINE. Otherwise, there will be JS errors.
     
    submenu[0]='<a href="">Page 1</a> | <a href="">Page 2</a>'

    submenu[1]='<a href="">Page 1</a> | <a href="">Page 2</a>'

    submenu[2]='<a href="">Page 1</a> | <a href="">Page 2</a>'

    submenu[3]='<a href="">Page 1</a> | <a href="">Page 2</a>'


    //Set delay before submenu disappears after mouse moves out of it (in milliseconds)
    var delay_hide=1500

    /////THE JAVASCRIPT FOLLOWS HERE AND WORKS FINE

     

     Another approach would be to have two versions of your menu in external JScript files, one with the admin link and one without.

    On Page_Load, use User.Identity.Name in a switch statement and load the appropriate menu file depending on whether the current user is one of your admins. I did a test case like this just now using a literal on a test page where I wanted the menu to appear, then based on my login name assigned the string <script type="\text/javascript"\ src=\"theAppropriateMenuFile.js\" /> to the text property of the literal. Worked like a charm. You could easily substitute groups, roles, or profile settings as the determining factor as well, depending on what you have enabled in your app.

    Be sure to protect your admin page with another method (put those pages in a folder with a web.config that restricts allowed users) in addition to just hiding the admin link. I'd never use navigation as security, only to keep the interface clean.

    I hope that helps...

    Greg
     

    "Give a man a fire and he'll stay warm for a day.
    Set a man on fire and he'll stay warm for the rest of his life."
Page 1 of 1 (7 items)