Compartir a través de


Utilizar la autenticación de formularios con AJAX en ASP.NET

Actualización: noviembre 2007

Puede usar el servicio de autenticación de aplicaciones de Microsoft AJAX Library para comprobar las credenciales almacenadas como parte del servicio de pertenencia de ASP.NET.

En este tema se muestra cómo llamar al servicio de autenticación de aplicaciones desde el explorador con JavaScript.

Puede tener acceso al servicio de autenticación del script de cliente si usa la clase AuthenticationService, que admite los métodos siguientes:

  • login. Este método valida las credenciales de usuario mediante el proveedor de suscripciones predeterminado. Si se comprueban las credenciales, el método envía una cookie de autenticación de formularios al explorador. La mayoría de las aplicaciones AJAX de ASP.NET usarán el método login, ya que las aplicaciones autenticadas por formularios requieren una cookie de autenticación en el explorador.

  • logout. Este método borra la cookie de autenticación de formularios.

Configurar el servidor

El servidor proporciona la infraestructura para procesar las credenciales de identificación como el nombre y la contraseña de un usuario, y para validar esas credenciales. La característica de autenticación mediante formularios permite autenticar el nombre de inicio de sesión y la contraseña de los usuarios mediante un formulario de inicio de sesión. Si la aplicación autentica la solicitud, el servidor emite un vale que contiene una clave con el fin de restablecer la identidad del usuario en posteriores solicitudes.

La clase AuthenticationService proporciona la clase de proxy de JavaScript a la que llama desde el script de cliente para comunicar con el servicio de autenticación en el servidor.

Nota:

Puede crear su propio servicio de autenticación de servidor. Para obtener más información, vea AuthenticationServiceManager.

Para admitir la autenticación en script de cliente, el servidor se debe configurar como se describe en las secciones siguientes.

Para obtener más información sobre la autenticación en ASP.NET, vea Funcionamiento de la seguridad en ASP.NET y Administrar usuarios mediante suscripciones.

Habilitar el servicio de autenticación

Para usar el servicio de autenticación del script de cliente, debe habilitarlo explícitamente con el siguiente elemento en el archivo Web.config de la aplicación:

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

Para obtener más información, vea Cómo: Configurar servicios de ASP.NET en ASP.NET AJAX.

El servicio de autenticación exige que la autenticación mediante formularios esté habilitada. El ejemplo siguiente muestra cómo habilitar la autenticación mediante formularios en el archivo Web.config de la aplicación.

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

El explorador debe tener las cookies habilitadas. El servicio de autenticación usa una cookie para el vale de autenticación que restablece la identidad del usuario en las solicitudes subsiguientes.

Configurar el acceso a la base de datos de suscripciones

De forma predeterminada, ASP.NET usa una base de datos SQL Server Express para almacenar la información de suscripción. La cadena de conexión de la base de datos se define en el archivo Machine.config y es similar a la que se muestra a continuación:

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

Si usa una base de datos diferente para obtener la información de suscripción, puede crear un elemento <connectionStrings> en el archivo Web.config de la aplicación que señale a esa base de datos. Para obtener más información, vea Configurar una aplicación ASP.NET para utilizar la suscripción.

Crear una carpeta restringida

Si desea limitar el acceso a información para que sólo los usuarios registrados puedan tener acceso a ella, debe crear un área restringida del sitio. Generalmente se trata de una carpeta bajo la raíz de la aplicación. Para limitar el acceso a la carpeta restringida, crea un archivo Web.config en la carpeta restringida y agrega una sección <authorization> en él. El ejemplo siguiente muestra el contenido de un archivo Web.config que sólo permite el acceso a los usuarios autenticados.

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

Ejemplo

En el ejemplo siguiente se muestra una página web ASP.NET que autentica al usuario mediante script de cliente. El ejemplo requiere que el servidor esté configurado como se ha descrito anteriormente en este tema. Se supone que el nombre de la carpeta restringida es Secured.

La página contiene un elemento <asp:ScriptManager>. Cuando este elemento se incluye en la página, el objeto AuthenticationService está automáticamente disponible para cualquier script de cliente de la página.

La página incluye un botón con un controlador de eventos asociado denominado OnClickLogin. El código del controlador de métodos llama al método login de la clase AuthenticationService.

Una vez iniciada la sesión, cambia el texto del botón y también cambia el texto en la parte superior de la página para indicar su estado de conexión. Haga clic en el vínculo de la parte inferior de la página para desplazarse a una página incluida en la carpeta Secured. Dado que ahora está registrado, puede tener acceso a las páginas en esta carpeta sin ser redirigido a la página de inicio de sesión.

En la página de ejemplo, puede hacer clic en un botón para cerrar sesión. Esta acción llama al controlador de eventos del botón OnClickLogout, que llama al método logout. Después de cerrar sesión, cambia el texto en la parte superior de la página. Si intenta tener acceso a la página en la carpeta Secured, se le redirigirá a la página de inicio de sesión, porque su explorador ya no tiene una cookie de autenticación mediante formularios.

El código de ejemplo proporciona funciones de devolución de llamada asincrónicas completas para los métodos login y logout. También puede crear funciones de devolución de llamada en caso de error para ambos métodos. Para obtener más información, vea el ejemplo que se incluye en la información general sobre la clase 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();

Vea también

Tareas

Cómo: Configurar servicios de ASP.NET en ASP.NET AJAX

Conceptos

Usar servicios web en ASP.NET para AJAX

Llamar a servicios web desde script de cliente

Usar información de funciones con AJAX en ASP.NET

Usar información de perfiles con AJAX en ASP.NET

Sys.Services.AuthenticationService (Clase)

Sys.Services.ProfileService (Clase)

Configurar una aplicación ASP.NET para utilizar la suscripción

Otros recursos

Funcionamiento de la seguridad en ASP.NET

Administrar usuarios mediante suscripciones