共用方式為


搭配 ASP.NET AJAX 使用表單驗證

更新:2007 年 11 月

您可以使用 Microsoft AJAX Library 應用程式驗證 (Authentication) 服務,驗證 (Verify) ASP.NET 成員資格服務中儲存的認證。

本主題顯示如何從瀏覽器中使用 JavaScript 呼叫應用程式驗證服務。

您可以從用戶端指令碼使用 AuthenticationService 類別存取驗證服務,這個類別支援下列方法:

  • login。這個方法會使用預設成員資格提供者來驗證使用者認證。驗證認證之後,這個方法會將表單驗證 Cookie 傳送至瀏覽器。大部分 ASP.NET AJAX 應用程式都使用 login 方法,因為表單驗證的應用程式需要瀏覽器中的驗證 Cookie。

  • logout。這個方法會清除表單驗證 Cookie。

設定伺服器

伺服器提供基礎結構來處理識別認證,例如使用者的名稱和密碼,並驗證這些認證。ASP.NET 的表單驗證功能可讓您使用登入表單驗證使用者的登入名稱和密碼。如果應用程式驗證要求,伺服器會發出包含金鑰的票證,以便於後續要求中重新建立使用者識別。

AuthenticationService 類別提供 JavaScript Proxy 類別,您可以從用戶端指令碼呼叫這個類別,與伺服器上的驗證服務通訊。

注意事項:

您可以建立自己的伺服器驗證服務。如需詳細資訊,請參閱AuthenticationServiceManager

為了在用戶端指令碼中支援驗證,必須如下列章節所述設定伺服器。

如需 ASP.NET 驗證的詳細資訊,請參閱ASP.NET 安全性的運作方式使用成員資格管理使用者

啟用驗證服務

若要從用戶端指令碼使用驗證服務,您必須在應用程式的 Web.config 檔案中使用下列項目,明確啟用驗證服務:

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

如需詳細資訊,請參閱 HOW TO:設定 ASP.NET AJAX 中的 ASP.NET 服務

驗證服務需要啟用表單驗證。下列範例顯示如何在應用程式的 Web.config 檔中啟用表單驗證。

<system.web>
  <authentication mode="Forms">
    <forms cookieless="UseCookies" 
      loginUrl="~/login.aspx"/>
  </authentication>
<system.web>
注意事項:

瀏覽器必須啟用 Cookie。驗證服務使用驗證票證的 Cookie,在後續要求中重新建立使用者的識別。

設定成員資格資料庫的存取

根據預設,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 Web 網頁。這個範例要求您必須已依照本主題稍早所述設定伺服器。受限制資料夾的名稱假設為 Secured。

網頁包含 <asp:ScriptManager> 項目。在網頁上加入這個項目時,網頁上的任何用戶端指令碼可以自動使用 AuthenticationService 物件。

網頁中有具有相關之事件處理常式的按鈕,名為 OnClickLogin。這個方法處理常式的程式碼會呼叫 AuthenticationService 類別的 login 方法。

在您登入之後,按鈕文字會變更,網頁頂端的文字也會變更來表示您已登入的狀態。按一下網頁底端的連結,可移至 Secured 資料夾中的網頁。因為現在已登入,您可以存取這個資料夾中的網頁,不會重新導向至登入網頁。

在範例網頁上,您可以按一下按鈕登出。這樣會呼叫 OnClickLogout 按鈕事件處理常式,這個處理常式會呼叫 logout 方法。在登出之後,網頁頂端的文字會變更。如果嘗試存取 secured 資料夾中的網頁,您將會重新導向至登入網頁,因為瀏覽器中已經沒有表單驗證 Cookie。

範例程式碼為 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();

請參閱

工作

HOW TO:設定 ASP.NET AJAX 中的 ASP.NET 服務

概念

在 ASP.NET AJAX 中使用 Web 服務

從用戶端指令碼呼叫 Web 服務

搭配 ASP.NET AJAX 使用角色資訊

搭配 ASP.NET AJAX 使用設定檔資訊

Sys.Services.AuthenticationService 類別

Sys.Services.ProfileService 類別

設定 ASP.NET 應用程式使用成員資格

其他資源

ASP.NET 安全性的運作方式

使用成員資格管理使用者