Αυτό το άρθρο βήμα προς βήμα περιγράφει τον τρόπο εμφάνισης μιας ASP.NET εφαρμογής να χρησιμοποιήσετε έλεγχο ταυτότητας φορμών για να επιτρέψετε στους χρήστες να πραγματοποιήσουν έλεγχο ταυτότητας σε υπηρεσία καταλόγου Active Directory χρησιμοποιώντας το Lightweight Directory Access Protocol (LDAP).
Αφού ο χρήστης είναι σε έλεγχο ταυτότητας και ανακατεύθυνση, μπορείτε να χρησιμοποιήσετε το
Application_AuthenticateRequestη μέθοδος του αρχείου Global.asax για την αποθήκευση ενός
GenericPrincipalαντικείμενο με το
HttpContext.Userιδιότητα που ρέει σε όλη τη διάρκεια της αίτησης.
Δημιουργία μιας εφαρμογής Web του ASP.NET στο Visual Basic .NET
Ακολουθήστε τα παρακάτω βήματα για να δημιουργήσετε μια νέα εφαρμογή Web του ASP.NET που ονομάζεται FormsAuthAd στη Visual Basic .NET:
- Ξεκινήστε το Microsoft Visual Studio .NET.
- Στο διακομιστήFILEμενού, σημείοΝέα, και στη συνέχεια κάντε κλικ στο κουμπίΤο έργο.
- Κάντε κλικΈργα της Visual BasicunderΤύποι έργου, και στη συνέχεια κάντε κλικ στο κουμπίΕφαρμογή Web του ASP.NETunderΠρότυπα.
- ΣτοΘέσηπληκτρολογήστεhttp:// <servername>/ FormsAuthAd</servername>(Αντικατάστασηhttp://localhostΕάν χρησιμοποιείτε τον τοπικό διακομιστή (ώστε να έχουνhttp://localhost/FormsAuthAd, και στη συνέχεια κάντε κλικ στο κουμπίOk.
- Κάντε δεξιό κλικ στοΑναφορέςκόμβος στο Solution Explorer και στη συνέχεια κάντε κλικΠροσθήκη αναφοράς.
- Στο διακομιστή.NETκαρτέλα με τοΠροσθήκη αναφοράςπαράθυρο διαλόγου, κάντε κλικ στο κουμπίSystem.DirectoryServices.dllΚάντε κλικΕπιλογή, και στη συνέχεια κάντε κλικ στο κουμπίOk.
Γράψτε τον κωδικό ελέγχου ταυτότητας
Ακολουθήστε τα παρακάτω βήματα για να δημιουργήσετε ένα νέο αρχείο κλάσης που ονομάζεται LdapAuthentication.vb:
- Στην Εξερεύνηση των λύσεων, κάντε δεξιό κλικ στον κόμβο του έργου, τοποθετήστε το δείκτηADD, και στη συνέχεια κάντε κλικ στο κουμπίΠροσθήκη νέου στοιχείου.
- Κάντε κλικCLASSunderΠρότυπα.
- TYPELdapAuthentication.vbΣτοNAMEπλαίσιο και στη συνέχεια κάντε κλικOpen.
- Αντικατάσταση του υπάρχοντος κώδικα στο αρχείο LdapAuthentication.vb με τον ακόλουθο κώδικα:
Imports System
Imports System.Text
Imports System.Collections
Imports System.DirectoryServices
Namespace FormsAuth
Public Class LdapAuthentication
Dim _path As String
Dim _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 DirectoryEntry = New DirectoryEntry(_path, domainAndUsername, pwd)
Try
'Bind to the native AdsObject to force authentication.
Dim obj As Object = entry.NativeObject
Dim search As DirectorySearcher = New DirectorySearcher(entry)
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 = CType(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 DirectorySearcher = New DirectorySearcher(_path)
search.Filter = "(cn=" & _filterAttribute & ")"
search.PropertiesToLoad.Add("memberOf")
Dim groupNames As StringBuilder = New StringBuilder()
Try
Dim result As SearchResult = search.FindOne()
Dim propertyCount As Integer = result.Properties("memberOf").Count
Dim dn As String
Dim equalsIndex, commaIndex
Dim propertyCounter As Integer
For propertyCounter = 0 To propertyCount - 1
dn = CType(result.Properties("memberOf")(propertyCounter), String)
equalsIndex = dn.IndexOf("=", 1)
commaIndex = dn.IndexOf(",", 1)
If (equalsIndex = -1) Then
Return Nothing
End If
groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1))
groupNames.Append("|")
Next
Catch ex As Exception
Throw New Exception("Error obtaining group names. " & ex.Message)
End Try
Return groupNames.ToString()
End Function
End Class
End Namespace
Επεξήγηση του κωδικού
Ο κωδικός ελέγχου ταυτότητας δέχεται έναν τομέα, όνομα χρήστη, κωδικό πρόσβασης και μια διαδρομή προς τη δομή της υπηρεσίας καταλόγου Active Directory. Αυτός ο κώδικας χρησιμοποιεί την υπηρεσία παροχής του καταλόγου LDAP.
Έλεγχος ταυτότητας χρήστη
Ο κώδικας στο Logon.aspx τη σελίδα κλήσεις του
LdapAuthentication.IsAuthenticatedη μέθοδος και περάσματα στις πιστοποιήσεις που συλλέγονται από το χρήστη. Στη συνέχεια, ένα
DirectoryEntryΔημιουργία αντικειμένου με τη διαδρομή προς τη δομή καταλόγου, το όνομα χρήστη και τον κωδικό πρόσβασης. Το όνομα χρήστη πρέπει να είναι στη μορφή "τομέας\όνομα_χρήστη".
Για να
DirectoryEntryαντικείμενο προσπαθεί, στη συνέχεια, για να επιβάλετε την
AdsObjectσύνδεση αποκτώντας το
NativeObjectΙδιότητα. Εάν επιτύχει, η
cnτο χαρακτηριστικό για το χρήστη λαμβάνονται από τη δημιουργία ενός
DirectorySearcherαντικείμενο και φιλτράρισμα κατά την
sAMAccountName. Αφού πιστοποιηθεί ο χρήστης, το
IsAuthenticatedη μέθοδος επιστρέφει
True.
ΣΗΜΕΙΩΣΗΌταν χρησιμοποιείτε το LDAP για να συνδέσετε σε ένα αντικείμενο που σχετίζονται με την υπηρεσία καταλόγου Active Directory, χρησιμοποιούνται οι θύρες TCP. Αυξημένη χρήση του LDAP με το
System.DirectoryServicesχώρος ονομάτων μπορεί να χρησιμοποιήσει όλες τις θύρες TCP που είναι διαθέσιμες. Μπορεί να είναι δυνατή η μείωση του φόρτου TCP με την επανάληψη χρήσης της σύνδεσης που χρησιμοποιείται για τον έλεγχο ταυτότητας του χρήστη.
Ομάδες χρηστών
Για να λάβετε μια λίστα των ομάδων που ανήκει ο χρήστης, αυτός ο κωδικός καλεί το
LdapAuthentication.GetGroupsΗ μέθοδος. Για να
LdapAuthentication.GetGroupsmethod obtains a list of security and distribution groups that
the user belongs to by creating a
DirectorySearcherobject and by filtering according to the
memberOfΧαρακτηριστικό. This method returns a list of groups that is separated
by pipes (|).
Προσέξτε ότι το
LdapAuthentication.GetGroupsmethod manipulates and truncates strings. This reduces the length
of the string that is stored in the authentication cookie. If the string is not
truncated, the format of each group appears as follows:
CN=...,...,DC=domain,DC=com
This can create a very long string. If the length of this string is
greater than the length of the cookie, the authentication cookie may not be
created. If this string may potentially be greater than the length of the
cookie, you may want to store the group information in the ASP.NET Cache object
or in a database. Alternatively, you may want to encrypt the group information
and store this information in a hidden form field.
Write the Global.asax Code
The code in the Global.asax file provides an
Application_AuthenticateRequestτο πρόγραμμα χειρισμού συμβάντων. This event handler retrieves the authentication
cookie from the
Context.Request.Cookiescollection, decrypts the cookie, and retrieves the list of groups
that will be stored in the
FormsAuthenticationTicket.UserDataΙδιότητα. The groups appear in a pipe-separated list that is
created in the Logon.aspx page.
The code parses the string in a
string array to create a
GenericPrincipalObject. Αφού το αρχείο
GenericPrincipalobject is created, this object is placed in the
HttpContext.UserΙδιότητα.
- Στην Εξερεύνηση των λύσεων, κάντε δεξιό κλικGlobal.asax, και στη συνέχεια κάντε κλικ στο κουμπίΠροβολή κώδικα.
- Add the following code at the top of the code, behind the
Global.asax.vb file:
Imports System.Web.Security
Imports System.Security.Principal
- Replace the existing empty event handler for theApplication_AuthenticateRequestμε τον ακόλουθο κώδικα:
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires upon attempting to authenticate the use
Dim cookieName As String = FormsAuthentication.FormsCookieName
Dim authCookie As HttpCookie = Context.Request.Cookies(cookieName)
If (authCookie Is Nothing) Then
'There is no authentication cookie.
Return
End If
Dim authTicket As FormsAuthenticationTicket = Nothing
Try
authTicket = FormsAuthentication.Decrypt(authCookie.Value)
Catch ex As Exception
'Write the exception to the Event Log.
Return
End Try
If (authTicket Is Nothing) Then
'Cookie failed to decrypt.
Return
End If
'When the ticket was created, the UserData property was assigned a
'pipe-delimited string of group names.
Dim groups As String() = authTicket.UserData.Split(New Char() {"|"})
'Create an Identity.
Dim id As GenericIdentity = New GenericIdentity(authTicket.Name, "LdapAuthentication")
'This principal flows throughout the request.
Dim principal As GenericPrincipal = New GenericPrincipal(id, groups)
Context.User = principal
End Sub
Modify the Web.config File
In this section, you configure the
formsΓια να
authenticationκαι το
authorizationelements in the Web.config file. With
these changes, only authenticated users can access the application, and
unauthenticated requests are redirected to a Logon.aspx page. You can modify
this configuration to permit only certain users and groups access to the
application.
Replace the existing code in the Web.config file with
the following code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="logon.aspx" name="adAuthCookie" timeout="60" path="/" >
</forms>
</authentication>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>
<identity impersonate="true" />
</system.web>
</configuration>
Notice the
identity impersonate="true" /configuration element. This causes ASP.NET to impersonate the account that is
configured as the anonymous account from Microsoft Internet Information
Services (IIS). As a result of this configuration, all requests to this
application run under the security context of the configured account. The user
provides credentials to authenticate against the Active Directory, but the
account that accesses the Active Directory is the configured account. For more
information, see the
ΑναφορέςΕνότητα.
Configure IIS for Anonymous Authentication
To configure IIS for anonymous authentication, follow these
steps:
- In the Internet Information Services (IIS) management
console, right-click the Virtual Directory node for"FormsAuthAd".
- Κάντε κλικ στην καρτέλαΙδιότητες (Properties), και στη συνέχεια κάντε κλικ στοΑσφάλεια καταλόγουTAB.
- Κάντε κλικΕπεξεργαστείτε τη διαδρομήunderAnonymous access and authentication control.
- Επιλέξτε τοΑνώνυμη πρόσβασηΠλαίσιο ελέγχου.
- Make the anonymous account for the application an account
that has permission to the Active Directory.
- Κάντε κλικ για να καταργήσετε την επιλογή τουAllow IIS To Control
PasswordΠλαίσιο ελέγχου.
The default IUSR_
computerNameλογαριασμός δεν έχει δικαίωμα της υπηρεσίας καταλόγου Active Directory.
Δημιουργία της σελίδας Logon.aspx
Ακολουθήστε τα παρακάτω βήματα για να δημιουργήσετε μια νέα φόρμα Web ASP.NET που ονομάζεται Logon.aspx:
- Στην Εξερεύνηση των λύσεων, κάντε δεξιό κλικ στον κόμβο του έργου, τοποθετήστε το δείκτηADD, και στη συνέχεια κάντε κλικ στο κουμπίΠροσθήκη φόρμας Web.
- TYPELogon.aspxΣτοNAMEπλαίσιο και στη συνέχεια κάντε κλικOpen.
- Στην Εξερεύνηση των λύσεων, κάντε δεξιό κλικLogon.aspx, και στη συνέχεια κάντε κλικ στο κουμπίΠροβολή "Σχεδίαση".
- Κάντε κλικ στην καρτέλαHTMLκαρτέλα στη σχεδίαση.
- Αντικαταστήστε τον υπάρχοντα κωδικό με τον ακόλουθο κώδικα:
<%@ Page language="vb" AutoEventWireup="true" %>
<%@ Import Namespace="FormsAuthAd.FormsAuth" %>
<html>
<body>
<form id="Login" method="post" runat="server">
<asp:Label ID="Label1" Runat="server">Domain:</asp:Label>
<asp:TextBox ID="txtDomain" Runat="server"></asp:TextBox><br>
<asp:Label ID="Label2" Runat="server">Username:</asp:Label>
<asp:TextBox ID="txtUsername" Runat="server"></asp:TextBox><br>
<asp:Label ID="Label3" Runat="server">Password:</asp:Label>
<asp:TextBox ID="txtPassword" Runat="server" TextMode="Password"></asp:TextBox><br>
<asp:Button ID="btnLogin" Runat="server" Text="Login" OnClick="Login_Click"></asp:Button><br>
<asp:Label ID="errorLabel" Runat="server" ForeColor="#ff3300"></asp:Label><br>
<asp:CheckBox ID="chkPersist" Runat="server" Text="Persist Cookie" />
</form>
</body>
</html>
<script runat="server">
sub Login_Click(sender as object,e as EventArgs)
Dim adPath as String = "LDAP://DC=..,DC=.." 'Path to your LDAP directory server
Dim adAuth as LdapAuthentication = new 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 FormsAuthenticationTicket = 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 HttpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
if(isCookiePersistent = true) 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
end sub
</script>
- Για να τροποποιήσετε τη διαδρομή στη σελίδα Logon.aspx ώστε να δείχνει προς το διακομιστή καταλόγου LDAP.
Στη σελίδα Logon.aspx είναι μια σελίδα που συλλέγει τις πληροφορίες από το χρήστη και η κλήση μεθόδων από το
LdapAuthenticationCLASS. Αφού ο κώδικας ελέγχει την ταυτότητα του χρήστη και αποκτά μια λίστα των ομάδων, ο κωδικός κάνει την εξής σειρά:
- δημιουργεί έναFormsAuthenticationTicketτο αντικείμενο;
- κρυπτογραφεί το εισιτήριο;
- Προσθέτει το εισιτήριο κρυπτογραφημένο cookie;
- Προσθέτει το cookie τουHttpResponse.Cookiesσυλλογή;
- ανακατευθύνει την αίτηση στη διεύθυνση URL που ζητήθηκε αρχικά.
Τροποποιήστε τη σελίδα WebForm1.aspx
Η σελίδα WebForm1.aspx είναι η σελίδα που ζητήσατε είναι αρχικά.
Όταν ο χρήστης ζητά αυτήν τη σελίδα, η αίτηση ανακατευθύνεται Logon.aspx τη σελίδα. Αφού έχει γίνει έλεγχος ταυτότητας της αίτησης, γίνεται ανακατεύθυνση της αίτησης στη σελίδα WebForm1.aspx.
- Στην Εξερεύνηση των λύσεων, κάντε δεξιό κλικWebForm1.aspx, και στη συνέχεια κάντε κλικ στο κουμπίΠροβολή "Σχεδίαση".
- Κάντε κλικ στην καρτέλαHTMLκαρτέλα στη σχεδίαση.
- Αντικαταστήστε τον υπάρχοντα κωδικό με τον ακόλουθο κώδικα:
<%@ Page language="vb" AutoEventWireup="true" %>
<%@ Import Namespace="System.Security.Principal" %>
<html>
<body>
<form id="Form1" method="post" runat="server">
<asp:Label ID="lblName" Runat="server" /><br>
<asp:Label ID="lblAuthType" Runat="server" />
</form>
</body>
</html>
<script runat="server">
sub Page_Load(sender as object, e as EventArgs)
lblName.Text = "Hello " + Context.User.Identity.Name & "."
lblAuthType.Text = "You were authenticated using " & Context.User.Identity.AuthenticationType & "."
end sub
</script>
- Αποθηκεύστε όλα τα αρχεία και στη συνέχεια να μεταγλωττίσετε το έργο.
- Αίτηση για τη σελίδα WebForm1.aspx. Παρατηρήστε ότι θα μεταφερθείτε σε Logon.aspx.
- Πληκτρολογήστε τις πιστοποιήσεις σύνδεσης και στη συνέχεια κάντε κλικ στο κουμπίΥποβολή. Όταν γίνει ανακατεύθυνση σε WebForm1.aspx, παρατηρήστε ότι εμφανίζεται το όνομα χρήστη σας και το οποίοLdapAuthenticationείναι ο τύπος ελέγχου ταυτότητας για τοContext.User.Identity.AuthenticationTypeΙδιότητα.
ΣΗΜΕΙΩΣΗΗ Microsoft συνιστά να χρησιμοποιήσετε Secure Sockets Layer (SSL) κρυπτογράφησης, όταν χρησιμοποιείτε έλεγχο ταυτότητας φορμών. Αυτό συμβαίνει επειδή ο χρήστης προσδιορίζεται με βάση το cookie ελέγχου ταυτότητας και κρυπτογράφησης SSL σε αυτήν την εφαρμογή σας εμποδίζει κάποιον σε κίνδυνο το cookie ελέγχου ταυτότητας και άλλες πολύτιμες πληροφορίες που μεταδίδεται.
Για περισσότερες πληροφορίες, κάντε κλικ στους αριθμούς των άρθρων παρακάτω για να προβάλετε τα άρθρα της Γνωσιακής Βάσης (Knowledge Base) της Microsoft:
306590
(http://support.microsoft.com/kb/306590/
)
Επισκόπηση της ασφάλειας ASP.NET
317012
(http://support.microsoft.com/kb/317012/
)
Ταυτότητα αίτησης και διαδικασίας στο ASP.NET
306238
(http://support.microsoft.com/kb/306238/
)
Τρόπος υλοποίησης με βάση τους ρόλους ασφαλείας με έλεγχο ταυτότητας που βασίζεται σε φόρμες της εφαρμογής ASP.NET με χρήση της Visual Basic .NET
313091
(http://support.microsoft.com/kb/313091/
)
Τρόπος δημιουργίας κλειδιών με χρήση της Visual Basic .NET για χρήση σε έλεγχο ταυτότητας φορμών
313116
(http://support.microsoft.com/kb/313116/
)
Οι αιτήσεις ελέγχου ταυτότητας φορμών δεν μεταβαίνετε στη σελίδα loginUrl