共用方式為


Using Forms Authentication with Microsoft Ajax

You can use the Microsoft Ajax Library application authentication service to verify credentials that are stored as part of the ASP.NET membership service.

This topic shows how to call the application authentication service from the browser by using JavaScript.

You can access the authentication service from client script by using the AuthenticationService class, which supports the following methods:

  • login. This method validates the user credentials by using the default membership provider. If the credentials are verified, the method sends a forms authentication cookie to the browser. Most ASP.NET AJAX applications will use the login method, because forms-authenticated applications require an authentication cookie in the browser.

  • logout. This method clears the forms authentication cookie.

Configuring the Server

The server provides the infrastructure to process the identification credentials such as name and password from a user, and to validate those credentials. The forms authentication feature in ASP.NET enables you to authenticate the user's login name and password users by using a login form. If the application authenticates the request, the server issues a ticket that contains a key for reestablishing the user identity in subsequent requests.

The AuthenticationService class provides the JavaScript proxy class that you call from client script to communicate with the authentication service on the server.

Note

You can create your own server authentication service. For more information, see AuthenticationServiceManager.

To support authentication in client script, the server must be configured as described in the following sections.

For more information about authentication in ASP.NET, see How ASP.NET Security Works and Managing Users by Using Membership.

Enabling the Authentication Service

To use the authentication service from client script, you must explicitly enable the authentication service by using the following element in the application's Web.config file:

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

For more information, see How to: Configure ASP.NET Services in Microsoft Ajax.

The authentication service requires forms authentication to be enabled. The following example shows how to enable forms authentication in the application's Web.config file.

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

Note

The browser must have cookies enabled. The authentication service uses a cookie for the authentication ticket that reestablishes the user's identity during subsequent requests.

Configuring Access to the Membership Database

By default, ASP.NET uses a SQL Server Express database to store membership information. The connection string for the database is defined in the Machine.config file and resembles the following:

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

If you are using a different database for membership information, you can create a <connectionStrings> element in the application Web.config file that points to that database. For more information, see Configuring an ASP.NET Application to Use Membership.

Creating a Restricted Folder

If you want to limit access to information so that only logged-in users can access it, you create a restricted area of the site. This is typically a folder under the application root. To limit access to the restricted folder, you create a Web.config file in the restricted folder and add an <authorization> section to it. The following example shows the contents of a Web.config file that restricts access to only authenticated users.

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

Example

The following example shows an ASP.NET Web page that authenticates the user by using client script. The example requires that you have configured the server as described earlier in this topic. The name of the restricted folder is assumed to be Secured.

The page contains an <asp:ScriptManager> element. When this element is included on the page, the AuthenticationService object is automatically available to any client script on the page.

The page has a button with an associated event handler named OnClickLogin. Code in the method handler calls the login method of the AuthenticationService class.

After you are logged in, the button text changes and the text at the top of the page changes to indicate your logged-in status. Click the link at the bottom of the page to move to a page located in the Secured folder. Because you are now logged in, you can access pages in this folder without being redirected to the login page.

On the sample page, you can click a button to log out. This calls the OnClickLogout button event handler, which calls the logout method. After you have logged out, the text at the top of the page changes. If you try to access the page in the secured folder, you will be redirected to the login page, because your browser no longer has a forms authentication cookie.

The example code provides asynchronous completed callback functions for the login and logout methods. You can also create failure callback functions for both methods. For more information, see the example provided in the AuthenticationService class overview.

<%@ Page Language="VB" %>

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


<html xmlns="https://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <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" runat="server">

        <asp:ScriptManager runat="server" 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" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="https://www.w3.org/1999/xhtml" >
<head runat="server">
    <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" runat="server">

        <asp:ScriptManager runat="server" 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();

See Also

Tasks

How to: Configure ASP.NET Services in Microsoft Ajax

Concepts

Using Roles Information with Microsoft Ajax

Using Profile Information with Microsoft Ajax

Sys.Services.AuthenticationService Class

Sys.Services.ProfileService Class

Configuring an ASP.NET Application to Use Membership

Other Resources

ASP.NET Web Services in AJAX

Calling Web Services from Client Script in ASP.NET AJAX

How ASP.NET Security Works

Managing Users by Using Membership