다음을 통해 공유


ASP.NET AJAX에서 폼 인증 사용

업데이트: 2007년 11월

Microsoft AJAX 라이브러리 응용 프로그램 인증 서비스를 사용하여 ASP.NET 멤버 자격 서비스의 일부로 저장되는 자격 증명을 확인할 수 있습니다.

이 항목에서 JavaScript를 사용하여 브라우저에서 응용 프로그램 인증 서비스를 호출하는 방법을 보여 줍니다.

다음 메서드를 지원하는 AuthenticationService 클래스를 사용하여 클라이언트 스크립트에서 인증 서비스에 액세스할 수 있습니다.

  • login. 이 메서드는 기본 멤버 자격 공급자를 사용하여 사용자 자격 증명의 유효성을 검사합니다. 자격 증명이 확인되면 이 메서드는 폼 인증 쿠키를 브라우저에 전달합니다. 폼 인증된 응용 프로그램은 브라우저에서 인증 쿠키를 요구하기 때문에 대부분의 ASP.NET AJAX 응용 프로그램에서는 login 메서드를 사용합니다.

  • logout. 이 메서드는 폼 인증 쿠키를 지웁니다.

서버 구성

서버에서 인프라를 제공하여 사용자의 이름과 암호와 같은 ID 자격 증명을 처리하고 해당 자격 증명의 유효성을 검사합니다. ASP.NET의 폼 인증 기능을 사용하면 로그인 폼을 통해 사용자의 로그인 이름과 암호를 인증할 수 있습니다. 응용 프로그램에서 요청을 인증하는 경우 서버에서는 후속 요청에서 사용자 ID를 다시 설정하는 키가 포함된 티켓을 발급합니다.

AuthenticationService 클래스에서는 클라이언트 스크립트에서 호출하는 JavaScript 프록시 클래스를 제공하여 서버의 인증 서비스와 통신합니다.

참고:

고유한 서버 인증 서비스를 만들 수 있습니다. 자세한 내용은 AuthenticationServiceManager를 참조하십시오.

클라이언트 스크립트에서 인증을 지원하려면 다음 단원에서 설명한 대로 서버를 구성해야 합니다.

ASP.NET의 인증에 대한 자세한 내용은ASP.NET 보안 작동 방법멤버 자격을 사용하여 사용자 관리를 참조하십시오.

인증 서비스 설정

클라이언트 스크립트에서 인증 서비스를 사용하려면 응용 프로그램의 Web.config 파일에서 다음 요소를 사용하여 인증 서비스를 명시적으로 설정해야 합니다.

<system.web.extensions>
  <scripting>
    <webServices>
      <authenticationService enabled="true" />
    </webServices>
  </scripting>
</system.web.extensions>

자세한 내용은 방법: ASP.NET AJAX에서 ASP.NET 서비스 구성을 참조하십시오.

인증 서비스를 사용하려면 폼 인증이 설정되어야 합니다. 다음 예제에서는 응용 프로그램의 Web.config 파일에서 폼 인증을 설정하는 방법을 보여 줍니다.

<system.web>
  <authentication mode="Forms">
    <forms cookieless="UseCookies" 
      loginUrl="~/login.aspx"/>
  </authentication>
<system.web>
참고:

브라우저에는 쿠키가 설정되어 있어야 합니다. 인증 서비스는 후속 요청 동안 사용자 ID를 다시 설정하는 인증 티켓에 대해 쿠키를 사용합니다.

멤버 자격 데이터베이스에 대한 액세스 구성

기본적으로 ASP.NET은 SQL Server Express 데이터베이스를 사용하여 멤버 자격 정보를 저장합니다. 데이터베이스에 대한 연결 문자열은 Machine.config 파일에 정의되며 다음과 유사합니다.

<connectionStrings>
  <add name="LocalSqlServer" 
  connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|aspnetdb.mdf;
User Instance=true" providerName="System.Data.SqlClient" />
</connectionStrings>

멤버 자격 정보에 대해 다른 데이터베이스를 사용하고 있는 경우 해당 데이터베이스를 가리키는 응용 프로그램 Web.config 파일에서 <connectionStrings> 요소를 만들 수 있습니다. 자세한 내용은 멤버 자격을 사용하도록 ASP.NET 응용 프로그램 구성을 참조하십시오.

제한된 폴더 만들기

로그인한 사용자만 액세스할 수 있도록 정보에 대한 액세스를 제한하려는 경우 해당 사이트에 대해 제한된 영역을 만듭니다. 이 영역은 일반적으로 응용 프로그램 루트 아래의 폴더입니다. 제한된 폴더에 대한 액세스를 제한하려면 제한된 폴더에서 Web.config 파일을 만들고 이 파일에 <authorization> 섹션을 추가합니다. 다음 예제에서는 인증된 사용자만 액세스할 수 있는 Web.config 파일의 내용을 보여 줍니다.

<?xml version="1.0"?>
<configuration>
  <system.web>
    <authorization>
      <deny users="?"/>
      <allow users="*"/>
    </authorization>
  </system.web>
</configuration>

예제

다음 코드 예제에서는 클라이언트 스크립트를 사용하여 사용자를 인증하는 ASP.NET 웹 페이지를 보여 줍니다. 이 예제에서는 이 항목의 앞부분에서 설명한 대로 서버를 구성해야 합니다. 제한된 폴더의 이름은 Secured로 간주됩니다.

페이지에는 <asp:ScriptManager> 요소가 있습니다. 이 요소가 페이지에 포함된 경우 페이지의 모든 클라이언트 스크립트에서 AuthenticationService 개체를 자동으로 사용할 수 있습니다.

페이지에는 OnClickLogin이라는 연결된 이벤트 처리기가 있는 단추가 있습니다. 메서드 처리기의 코드는 AuthenticationService 클래스의 login 메서드를 호출합니다.

로그인한 후 단추 텍스트가 변경되고 페이지의 맨 위에 있는 텍스트가 변경되어 로그인 상태를 나타냅니다. 페이지 아래쪽의 링크를 클릭하여 Secured 폴더에 있는 페이지로 이동합니다. 이제 로그인되어 있으므로 로그인 페이지로 리디렉션되지 않고 이 폴더의 페이지에 액세스할 수 있습니다.

샘플 페이지에서 단추를 클릭하여 로그아웃할 수 있습니다. 이렇게 하면 logout 메서드를 호출하는 OnClickLogout 단추 이벤트 처리기를 호출합니다. 로그아웃한 후에 페이지 맨 위에 있는 텍스트가 변경됩니다. 보안 폴더의 페이지에 액세스하려고 하면 브라우저에 폼 인증 쿠키가 더 이상 없기 때문에 로그인 페이지로 리디렉션됩니다.

예제 코드에서는 loginlogout 메서드에 대해 비동기로 완료된 콜백 함수를 제공합니다. 또한 양쪽 메서드에 실패 콜백 함수를 만들 수 있습니다. 자세한 내용은 AuthenticationService 클래스 개요에 제공된 예제를 참조하십시오.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" >
    <title>Authentication Service</title>
    <style type="text/css">
        body {  font: 11pt Trebuchet MS;
                font-color: #000000;
                padding-top: 72px;
                text-align: center }

        .text { font: 8pt Trebuchet MS }
    </style>
</head>
<body>
      <form id="form1" >

        <asp:ScriptManager  ID="ScriptManagerId">
            <Scripts>
                <asp:ScriptReference Path="Authentication.js" />
            </Scripts>
        </asp:ScriptManager>

        <h2>Authentication Service</h2>

            <span id="loggedin" 
                style="visibility:hidden; color:Green; font-weight:bold; font-size:large" 
                visible="false"><b>You are logged in! </b>
            </span> 

            <span id="notloggedin" 
                style="visibility:visible;color:Red; font-weight:bold; font-size:large">
                You are logged out!    
                <br /> <br />
                <span style="font-weight:normal; font-size:medium; color:Black">
                    Please, use one of the following [username, password] 
                    combinations:<br />
                    [user1, u$er1] <br/>
                    [user2, u$er2] <br/> 
                    [user3, u$er3]   
                </span>   
            </span>


        <br /><br />
        <div>
        <table>
            <tr id="NameId"  style="visibility:visible;">
                <td style="background-color:Yellow; font-weight:bold; color:Red">
                    User Name:
                </td>
                <td>
                    <input type="text" id="username"/>
                </td> 
            </tr>
            <tr id="PwdId"  style="visibility:visible;">
               <td style="background-color:Yellow; font-weight:bold; color:Red">
                    Password:
                </td>
                <td>
                    <input type="password" id="password" />
                </td> 
            </tr>   
            <tr>
                <td colspan="2" align="center">
                    <button id="ButtonLogin"   
                        style="background-color:Aqua;"
                        onclick="OnClickLogin(); return false;">Login</button>
                    <button id="ButtonLogout"   
                        style="background-color:Aqua; visibility:hidden;"
                        onclick="OnClickLogout(); return false;">Logout</button>
                </td> 
            </tr>          
        </table>
        <br />
        <br />
        <a href="secured/Default.aspx" target="_top2" >
            Attempt to access a page 
            that requires authenticated users.</a>
        <br />
        <br />
        <!-- <a href="CreateNewUser.aspx"><b>Create a new user.</b></a>
        -->        
        </div>

   </form>

   <hr />

   <div id="FeedBackID" style="visibility:visible" />


</body>
</html>
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" >
<head >
    <title>Authentication Service</title>
    <style type="text/css">
        body {  font: 11pt Trebuchet MS;
                font-color: #000000;
                padding-top: 72px;
                text-align: center }

        .text { font: 8pt Trebuchet MS }
    </style>
</head>
<body>
      <form id="form1" >

        <asp:ScriptManager  ID="ScriptManagerId">
            <Scripts>
                <asp:ScriptReference Path="Authentication.js" />
            </Scripts>
        </asp:ScriptManager>

        <h2>Authentication Service</h2>

            <span id="loggedin" 
                style="visibility:hidden; color:Green; font-weight:bold; font-size:large" 
                visible="false"><b>You are logged in! </b>
            </span> 

            <span id="notloggedin" 
                style="visibility:visible;color:Red; font-weight:bold; font-size:large">
                You are logged out!    
                <br /> <br />
                <span style="font-weight:normal; font-size:medium; color:Black">
                    Please, use one of the following [username, password] 
                    combinations:<br />
                    [user1, u$er1] <br/>
                    [user2, u$er2] <br/> 
                    [user3, u$er3]   
                </span>   
            </span>


        <br /><br />
        <div>
        <table>
            <tr id="NameId"  style="visibility:visible;">
                <td style="background-color:Yellow; font-weight:bold; color:Red">
                    User Name:
                </td>
                <td>
                    <input type="text" id="username"/>
                </td> 
            </tr>
            <tr id="PwdId"  style="visibility:visible;">
               <td style="background-color:Yellow; font-weight:bold; color:Red">
                    Password:
                </td>
                <td>
                    <input type="password" id="password" />
                </td> 
            </tr>   
            <tr>
                <td colspan="2" align="center">
                    <button id="ButtonLogin"   
                        style="background-color:Aqua;"
                        onclick="OnClickLogin(); return false;">Login</button>
                    <button id="ButtonLogout"   
                        style="background-color:Aqua; visibility:hidden;"
                        onclick="OnClickLogout(); return false;">Logout</button>
                </td> 
            </tr>          
        </table>
        <br />
        <br />
        <a href="secured/Default.aspx" target="_top2" >
            Attempt to access a page 
            that requires authenticated users.</a>
        <br />
        <br />
        <!-- <a href="CreateNewUser.aspx"><b>Create a new user.</b></a>
        -->        
        </div>

   </form>

   <hr />

   <div id="FeedBackID" style="visibility:visible" />


</body>
</html>
var usernameEntry;
var passwordEntry;
var username;
var password;
var textLoggedIn;
var textNotLoggedIn;
var buttonLogin;  
var buttonLogout; 

function pageLoad()
{
    usernameEntry = $get("NameId");
    passwordEntry = $get("PwdId");
    username = $get("username");
    password = $get("password");
    textLoggedIn = $get("loggedin");
    textNotLoggedIn = $get("notloggedin");
    buttonLogin = $get("ButtonLogin");  
    buttonLogout = $get("ButtonLogout"); 
}            

// This function sets and gets the default
// login completed callback function.
function SetDefaultLoginCompletedCallBack()
{
    // Set the default callback function.
    Sys.Services.AuthenticationService.set_defaultLoginCompletedCallback(OnLoginCompleted);

    // Get the default callback function.
    var callBack =     
        Sys.Services.AuthenticationService.get_defaultLoginCompletedCallback();
}

// This function sets and gets the default
// logout completed callback function.
function SetDefaultLogoutCompletedCallBack()
{
    // Set the default callback function.
    Sys.Services.AuthenticationService.set_defaultLogoutCompletedCallback(OnLogoutCompleted);

    // Get the default callback function.
    var callBack =     
        Sys.Services.AuthenticationService.get_defaultLogoutCompletedCallback();
}

// This function sets and gets the default
// failed callback function.
function SetDefaultFailedCallBack()
{
    // Set the default callback function.
    Sys.Services.AuthenticationService.set_defaultFailedCallback(OnFailed);

    // Get the default callback function.
    var callBack =     
        Sys.Services.AuthenticationService.get_defaultFailedCallback();
}

// This function calls the login method of the
// authentication service to verify 
// the credentials entered by the user.
// If the credentials are authenticated, the
// authentication service issues a forms 
// authentication cookie. 
function OnClickLogin() 
{   
    // Set the default callback functions.
    SetDefaultLoginCompletedCallBack();
    SetDefaultLogoutCompletedCallBack();
    SetDefaultFailedCallBack();

    // Call the authetication service to authenticate
    // the credentials entered by the user.
    Sys.Services.AuthenticationService.login(username.value, 
        password.value, false,null,null,null,null,"User Context");
}

// This function calls the logout method of the
// authentication service to clear the forms 
// authentication cookie.
function OnClickLogout() 
{  
   // Clear the forms authentication cookie. 
   Sys.Services.AuthenticationService.logout(null, 
        null, null, null); 
} 

// This is the callback function called 
// if the authentication fails.      
function OnFailed(error, 
    userContext, methodName)
{           
    // Display feedback message.
    DisplayInformation("error:message = " + 
        error.get_message());
    DisplayInformation("error:timedOut = " + 
        error.get_timedOut());
    DisplayInformation("error:statusCode = " + 
        error.get_statusCode());            
}


// The callback function called 
// if the authentication completed successfully.
function OnLoginCompleted(validCredentials, 
    userContext, methodName)
{
    
    // Clear the user password.
    password.value = "";

    // On success there will be a forms 
    // authentication cookie in the browser.
    if (validCredentials == true) 
    {

        // Clear the user name.
        username.value = "";

        // Hide login fields.
        buttonLogin.style.visibility = "hidden";
        usernameEntry.style.visibility = "hidden";
        passwordEntry.style.visibility = "hidden";
        textNotLoggedIn.style.visibility = "hidden";  

        // Display logout fields.
        buttonLogout.style.visibility = "visible";
        textLoggedIn.style.visibility = "visible";

        // Clear the feedback area.
        DisplayInformation(""); 
    }
    else 
    {
        textLoggedIn.style.visibility = "hidden";
        textNotLoggedIn.style.visibility = "visible";
        DisplayInformation(
            "Login Credentials Invalid. Could not login"); 
    }
}

// This is the callback function called 
// if the user logged out successfully.
function OnLogoutCompleted(result) 
{
    // Display login fields.
    usernameEntry.style.visibility = "visible";
    passwordEntry.style.visibility = "visible";
    textNotLoggedIn.style.visibility = "visible";  
    buttonLogin.style.visibility = "visible";

    // Hide logout fields.
    buttonLogout.style.visibility = "hidden";
    textLoggedIn.style.visibility = "hidden";
}                   

// This function displays feedback
// information for the user.    
function DisplayInformation(text)
{
    document.getElementById("FeedBackID").innerHTML = 
        "<br/>" + text;

    // Display authentication service information.


    var userLoggedIn =
        Sys.Services.AuthenticationService.get_isLoggedIn();
    
    var authServiceTimeout =       
        Sys.Services.AuthenticationService.get_timeout();

    var userLoggedInfo = 
        "<br/> User logged in:                 " + userLoggedIn;

    var timeOutInfo = 
        "<br/> Authentication service timeout: " + authServiceTimeout;

    document.getElementById("FeedBackID").innerHTML = 
        userLoggedInfo + timeOutInfo; 
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

참고 항목

작업

방법: ASP.NET AJAX에서 ASP.NET 서비스 구성

개념

ASP.NET AJAX의 웹 서비스 사용

클라이언트 스크립트에서 웹 서비스 호출

ASP.NET AJAX에서 역할 정보 사용

ASP.NET AJAX에서 프로필 정보 사용

Sys.Services.AuthenticationService 클래스

Sys.Services.ProfileService 클래스

멤버 자격을 사용하도록 ASP.NET 응용 프로그램 구성

기타 리소스

ASP.NET 보안 작동 방법

멤버 자격을 사용하여 사용자 관리