开发者

Windows Authentication for Intranet Users at the App Level (ASP.NET with VB)

My company uses ActiveDirectory, and naturally the IT department wants to maintain control over it and not give control to other users. I'm developing an ASP.NET app (for internal use only) using an SQL Server 2008 database.

My question is, how can I BEST use the .NET namespaces and SQL Server to manage access to the app within the organization at the application (or possibly DB) level? I would like the user to be authorized based on their network username as provided by ActiveDirectory.

On a side note, I would also like to access their AD contact information.

From my understanding I can use the ActiveDirectoryMembershipProvider class or Domain Services in the System.DirectoryServices namespace. There's also LDAP which apparently is another possibility. I'm having a hard time m开发者_开发知识库aking sense of it all, and much less which is the best option and how to implement it. Can anyone provide me with some direction and possibly some simple sample code?

UPDATE: Sorry, I forgot to mention I'm using VB.NET as my code source as it's company standard.

Much obliged! ;)


Here's a quick code snippet that started me on my never ending journey with Active Directory and ASP.NET. It's from a little test page that I put a text box and plugged in a LAN ID and it returns all the AD fields available.

    Protected Sub btnSearchUserDetails_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearchUserDetails.Click
    Dim Entry1 As New System.DirectoryServices.DirectoryEntry("LDAP://DC=ent,DC=foo,DC=bar,DC=corp", "yourID", "yourPassword")
    Dim search As New DirectorySearcher(Entry1)
    search.Filter = [String].Format("(SAMAccountName={0})", txtSearchUser.Text)

    Dim result As SearchResult = search.FindOne()
    Dim user As DirectoryEntry = result.GetDirectoryEntry()
    PrintDirectoryEntryProperties(user)
    End Sub

Private Sub PrintDirectoryEntryProperties(ByVal entry As System.DirectoryServices.DirectoryEntry)


    'loop through all the properties and get the key for each prop


    lblPropList.Text = "<table>"
    For Each Key As String In entry.Properties.PropertyNames
        Dim sPropertyValues As String = [String].Empty
        'now loop through all the values in the property;
        'can be a multi-value property
        For Each Value As Object In entry.Properties(Key)
            sPropertyValues += Convert.ToString(Value) + ";<br>"
        Next
        'cut off the separator at the end of the value list
        sPropertyValues = sPropertyValues.Substring(0, sPropertyValues.Length - 5)
        'now add the property info to the property list

            lblPropList.Text += "<tr><td>" & Key & "</td><td>" & sPropertyValues & "</td></tr>"

    Next
    lblPropList.Text += "</table>"

End Sub

To get the AD login ID of the currently authenticated user Request.ServerVariables("LOGON_USER") and Httpcontext.Current.User.Identity.Name are going to be your friends. Keep in mind that the LOGON_USER variable is not populated if you use the Allow Anonymous security to access the ASP page.

I'll go back through some of my notes and try to find some of the resources that I used that ended up being the most helpful for me. Off the top of my head, I can tell you that the book "The .NET Developer's Guide to Directory Services Programming" (Amazon) was used daily by me.


As I later come to find out, Windows authentication mode works perfectly within an intranet environment. I decided to enable this mode in my IIS configuration while developing and have each page automatically identify the user by their network login and point them (or allow/disallow access to the appropriate pages). Keep in mind that my solution ONLY works on an intranet / if you're on a domain controller.

Here's the relevant Web.config

<system.web>
    <authentication mode="Windows" />
    <identity impersonate="false" />
</system.web>

The simplest approach I think is to lookup the username in the database and find their associated role/group, then evaluate whether or not that role should give them access to the requested page in the VB codebehind. Here's how to get the users network username:

' While logged into your intranet will return "DOMAIN\username"
Dim username As String = Page.User.Identity.Name

Here's some sample VB.NET code that can be used for authenticating (automatically) and allowing access to a given page (not precisely the code I used, just a sample).

Dim role As String
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("conString").ConnectionString)
    Dim query As New SqlCommand("select top (1) Role from Users where Username like '" + username + "'", con)
    con.Open()
    role = query.ExecuteScalar().ToString
End Using
If StrComp(role, "Admin") = 0 Then
    welcomeLabel.Text = "Welcome! You may enter"
Else
    HttpContext.Current.Server.Transfer("/Kick.aspx")
End If

I hope some people find this useful. I spent countless hours settling on a solution almost identical to this.

Cheers ;)


The accepted answer using "lookup the username in the database and find their associated role/group" IMHO is missing the whole point.

The solution is to check NTLM Authentication check box in Visual Studio (using version 2012 is under project's Properties, Web, Servers; other version should be similar).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜