태터데스크 관리자

도움말
닫기
적용하기   첫페이지 만들기

태터데스크 메시지

저장하였습니다.
페이지를 읽고 있습니다. ( 아쿠아바다's Blog )
분류 전체보기 (769)
쉐어포인트 (24)
Exchange (12)
SQL (121)
XML (36)
WEB (294)
O / S (97)
삶의향기 (162)
기획 (19)
RSS 피드(IE 7.0부터 기본 지원됩니다. 이전 버전 사용자는 접합한 툴을 사용하세요!!)

HOWTO: 폼 인증 및 Visual Basic .NET을 사용한 Active Directory 인증

기술 자료 ID : 326340
마지막 검토 : 2005년 7월 11일 월요일
수정 : 3.1

요약

이 문서에서는 ASP.NET 응용 프로그램에서 LDAP(Lightweight Directory Access Protocol)를 사용하여 Active Directory에 대해 사용자를 인증할 수 있도록 폼 인증을 사용하는 방법을 단계별로 설명합니다.

사용자가 인증되고 리디렉션된 후에는 Global.asax 파일의 Application_AuthenticateRequest 메서드를 사용하여, 요청 처리 과정에 사용되는 HttpContext.User 속성에 GenericPrincipal 개체를 저장할 수 있습니다.

맨 위로 (http://support.microsoft.com/?scid=toc)

Visual Basic .NET에서 ASP.NET 웹 응용 프로그램 만들기

Visual Basic .NET에서 다음 단계를 수행하여 FormsAuthAd라는 새 ASP.NET 웹 응용 프로그램을 만듭니다.
1. Microsoft Visual Studio .NET을 시작합니다.
2. 파일 메뉴에서 새로 만들기를 가리킨 다음 프로젝트를 누릅니다.
3. 프로젝트 형식에서 Visual Basic 프로젝트를 누른 다음 템플릿에서 ASP.NET 웹 응용 프로그램을 누릅니다.
4. 위치 상자에 http://<서버 이름>/FormsAuthAd를 입력합니다. 로컬 서버를 사용하는 경우에는 http://localhost를 대신 사용합니다(예: http://localhost/FormsAuthAd). 그런 다음 확인을 누릅니다.
5. 솔루션 탐색기에서 참조 노드를 마우스 오른쪽 단추로 누른 다음 참조 추가를 누릅니다.
6. 참조 추가 대화 상자의 .NET 탭에서 System.DirectoryServices.dll을 누르고 선택을 누른 다음 확인을 누릅니다.
맨 위로 (http://support.microsoft.com/?scid=toc)

인증 코드 작성

다음 단계를 수행하여 LdapAuthentication.vb라는 새 클래스 파일을 만듭니다.
1. 솔루션 탐색기에서 프로젝트 노드를 마우스 오른쪽 단추로 누르고 추가를 가리킨 다음 새 항목 추가를 누릅니다.
2. 템플릿 아래에서 클래스를 누릅니다.
3. 이름 상자에 LdapAuthentication.vb를 입력한 다음 열기를 누릅니다.
4. 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 개체가 NativeObject 속성을 얻어 AdsObject를 강제로 바인딩하려고 시도합니다. 바인딩에 성공하면 DirectorySearcher 개체를 만들고 SAMAccountName을 기준으로 필터링하여 사용자에 대한 CN 특성을 얻게 됩니다. 사용자가 인증된 후 IsAuthenticated 메서드는 true를 반환합니다.

사용자 그룹

사용자가 속해 있는 그룹의 목록을 얻기 위해 이 코드는 LdapAuthentication.GetGroups 메서드를 호출합니다. LdapAuthentication.GetGroups 메서드는 DirectorySearcher 개체를 만들고 memberOf 특성에 따라 필터링하여 사용자가 속해 있는 보안 및 배포 그룹의 목록을 가져옵니다. 이 메서드는 파이프 기호(|)로 구분된 그룹 목록을 반환합니다.

LdapAuthentication.GetGroups 메서드는 문자열을 조작하고 자름으로써 인증 쿠키에 저장되는 문자열의 길이를 줄입니다. 문자열이 잘리지 않은 경우 각 그룹은 다음과 같은 형식으로 나타납니다.
CN=...,...,DC=domain,DC=com
				
이 경우 매우 긴 문자열이 만들어질 수 있습니다. 이 문자열의 길이가 쿠키의 길이보다 길면 인증 쿠키를 만들 수 없습니다. 이 문자열의 길이가 쿠키의 길이보다 길 가능성이 있는 경우에는 그룹 정보를 ASP.NET 캐시 개체나 데이터베이스에 저장할 수 있습니다. 또는 그룹 정보를 암호화하고 이 정보를 숨겨진 폼 필드에 저장할 수 있습니다.

맨 위로 (http://support.microsoft.com/?scid=toc)

Global.asax 코드 작성

Global.asax 파일의 코드는 Application_AuthenticateRequest 이벤트 처리기를 제공합니다. 이 이벤트 처리기는 Context.Request.Cookies 컬렉션에서 인증 쿠키를 검색하고, 쿠키를 해독하고, FormsAuthenticationTicket.UserData 속성에 저장될 그룹 목록을 검색합니다. 이 그룹은 Logon.aspx 페이지에 만들어지는 파이프 기호로 구분된 목록에 나타납니다.

이 코드는 문자열 배열의 문자열을 분석하여 GenericPrincipal 개체를 만듭니다. GenericPrincipal 개체가 만들어진 후 이 개체는 HttpContext.User 속성에 보관됩니다.
1. 솔루션 탐색기에서 Global.asax를 마우스 오른쪽 단추로 누른 다음 코드 보기를 누릅니다.
2. Global.asax.vb 파일에서 코드의 맨 위에 다음 코드를 추가합니다.
Imports System.Web.Security
Imports System.Security.Principal
					
3. Application_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
					
맨 위로 (http://support.microsoft.com/?scid=toc)

Web.config 파일 수정

이 단계에서는 Web.config 파일의 forms, authenticationauthorization 요소를 구성합니다. 이러한 요소를 변경하면 인증된 사용자만 응용 프로그램에 액세스할 수 있게 되고 인증되지 않은 요청은 Logon.aspx 페이지로 리디렉션됩니다. 이 구성을 수정하여 일부 사용자 및 그룹만 응용 프로그램에 액세스하도록 허용할 수 있습니다.

Web.config 파일의 기존 코드를 다음 코드로 바꿉니다.
<?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>
				
여기서 identity impersonate="true" / 구성 요소에 주의하십시오. 이 요소를 구성하면 ASP.NET에서는 Microsoft 인터넷 정보 서비스(IIS)에서 익명 계정으로 구성된 계정을 가장하게 됩니다. 이 구성의 결과 해당 응용 프로그램에 대한 모든 요청은 구성된 계정의 보안 컨텍스트에서 실행됩니다. 사용자는 자격 증명을 제공하여 Active Directory에 대한 권한을 인증하지만 Active Directory에 액세스하는 계정은 구성된 계정입니다. 자세한 내용은 참조 절을 참조하십시오.

맨 위로 (http://support.microsoft.com/?scid=toc)

익명 인증을 위한 IIS 구성

IIS에 익명 인증을 구성하려면 다음 단계를 수행하십시오.
1. 인터넷 정보 서비스(IIS) 관리 콘솔에서 "FormsAuthAd"에 대한 가상 디렉터리 노드를 마우스 오른쪽 단추로 누릅니다.
2. 속성을 누른 다음 디렉터리 보안 탭을 누릅니다.
3. 익명 액세스 및 인증 제어에서 편집을 누릅니다.
4. 익명 액세스 확인란을 선택합니다.
5. 응용 프로그램에 대한 익명 계정과 Active Directory 사용 권한이 있는 계정을 만듭니다.
6. IIS에서 암호 제어 허용 확인란의 선택을 취소합니다.
기본 IUSR_컴퓨터 이름 계정에는 Active Directory에 대한 사용 권한이 없습니다.

맨 위로 (http://support.microsoft.com/?scid=toc)

Logon.aspx 페이지 만들기

다음 단계를 수행하여 Logon.aspx라는 새 ASP.NET Web Form을 만듭니다.
1. 솔루션 탐색기에서 프로젝트 노드를 마우스 오른쪽 단추로 누르고 추가를 가리킨 다음 Web Form 추가를 누릅니다.
2. 이름 상자에 Logon.aspx를 입력한 다음 열기를 누릅니다.
3. 솔루션 탐색기에서 Logon.aspx를 마우스 오른쪽 단추로 누른 다음 디자이너 보기를 누릅니다.
4. 디자이너에서 HTML 탭을 누릅니다.
5. 기존 코드를 다음 코드로 바꿉니다.
<%@ 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>
					
6. Logon.aspx 페이지에 있는 경로를 LDAP 디렉터리 서버 경로로 수정합니다.
Logon.aspx 페이지는 사용자로부터 정보를 수집하고 LdapAuthentication 클래스의 메서드를 호출하는 페이지입니다. 사용자를 인증하고 그룹 목록을 가져온 후에는 다음 작업이 순서대로 수행됩니다.
FormsAuthenticationTicket 개체를 만듭니다.
티켓을 암호화합니다.
암호화된 티켓을 쿠키에 추가합니다.
이 쿠기를 HttpResponse.Cookies 컬렉션에 추가합니다.
원래 요청되었던 URL로 요청을 리디렉션합니다.
맨 위로 (http://support.microsoft.com/?scid=toc)

WebForm1.aspx 페이지 수정

WebForm1.aspx 페이지는 원래 요청되었던 페이지입니다. 사용자가 이 페이지를 요청하면 요청은 Logon.aspx 페이지로 리디렉션됩니다. 요청이 인증된 후에는 WebForm1.aspx 페이지로 요청이 리디렉션됩니다.
1. 솔루션 탐색기에서 WebForm1.aspx를 마우스 오른쪽 단추로 누른 다음 디자이너 보기를 누릅니다.
2. 디자이너에서 HTML 탭을 누릅니다.
3. 기존 코드를 다음 코드로 바꿉니다.
<%@ 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>
					
4. 모든 파일을 저장한 다음 프로젝트를 컴파일합니다.
5. WebForm1.aspx 페이지를 요청합니다. 그러면 Logon.aspx로 리디렉션됩니다.
6. 로그온 자격 증명을 입력한 다음 전송을 누릅니다. WebForm1.aspx로 리디렉션되면 사용자 이름이 나타나고 LdapAuthenticationContext.User.Identity.AuthenticationType 속성의 인증 유형이 됩니다.
참고: 폼 인증을 사용할 때는 SSL(Secure Sockets Layer) 암호화를 사용하는 것이 좋습니다. 사용자가 인증 쿠키를 기준으로 식별되고, 이 응용 프로그램에 SSL 암호화를 사용하면 다른 사용자가 전송되는 인증 쿠키와 다른 중요한 정보를 손상시키지 못하게 되기 때문입니다.

맨 위로 (http://support.microsoft.com/?scid=toc)

참조

자세한 내용은 Microsoft 기술 자료의 다음 문서를 참조하십시오.
306590 (http://support.microsoft.com/kb/306590/) INFO: ASP.NET 보안 개요
317012 (http://support.microsoft.com/kb/317012/) INFO: ASP.NET에서 프로세스 및 요청 ID
306238 (http://support.microsoft.com/kb/306238/) HOWTO: Visual Basic .NET을 사용하여 ASP.NET 응용 프로그램에서 폼 기반 인증을 가진 역할 기반 보안을 구현하는 방법
313091 (http://support.microsoft.com/kb/313091/) HOWTO: Visual Basic .NET을 사용하여 Forms 인증에서 사용할 키 만들기
313116 (http://support.microsoft.com/kb/313116/) PRB: 폼 인증 요청이 loginUrl 페이지로 리디렉션되지 않는다
맨 위로 (http://support.microsoft.com/?scid=toc)



Microsoft 제품 관련 기술 전문가들과 온라인으로 정보를 교환하시려면 Microsoft 뉴스 그룹 (http://support.microsoft.com/newsgroups/default.aspx)에 참여하시기 바랍니다.

본 문서의 정보는 다음의 제품에 적용됩니다.
Microsoft ASP.NET 1.0
Microsoft Visual Basic .NET 2002 Standard Edition
Microsoft ASP.NET 1.1
Microsoft Visual Basic .NET 2003 Standard Edition
키워드:
kbconfig kbcookie kbhowtomaster kbsecurity kbwebforms KB326340
좀더 흥미로운 내용이 많이 있습니다.. HOME > O / S/WINDOWS를 확인하세요
0 Trackback, 0 Comment, :
1  ... 378 379 380 381 382 383 384 385 386  ... 769 
Statistics Graph
Total : 557,403 Today : 33