ASP.NET AJAX でのフォーム認証の使用

更新 : 2007 年 11 月

Microsoft AJAX Library アプリケーション認証サービスを使用すると、ASP.NET メンバシップ サービスの一部として保存されている資格情報を確認できます。

このトピックでは、JavaScript を使用してブラウザからアプリケーション認証サービスを呼び出す方法を説明します。

AuthenticationService クラスを使用することで、クライアント スクリプトから認証サービスにアクセスできます。このクラスは、次のメソッドをサポートしています。

  • login。このメソッドは、既定のメンバシップ プロバイダを使用してユーザー資格情報を検証します。資格情報が正しいことを確認すると、このメソッドはフォーム認証 Cookie をブラウザに送信します。login メソッドはほとんどの ASP.NET AJAX アプリケーションで使用されます。これは、フォーム認証を使用するアプリケーションでは、ブラウザ内の認証 Cookie が必要となるためです。

  • logout。このメソッドはフォーム認証 Cookie をクリアします。

サーバーの構成

サーバーは、名前やパスワードなど、ユーザーを識別するための資格情報を処理し、それらの資格情報を検証するためのインフラストラクチャを提供します。ASP.NET のフォーム認証機能により、ログイン フォームを使用してユーザーのログイン名とパスワードを認証できます。アプリケーションで要求を認証する場合、後続の要求で使用するユーザー ID を再確立するためのキーが含まれたチケットをサーバーが発行します。

AuthenticationService クラスは、JavaScript プロキシ クラスを提供しています。このクラスをクライアント スクリプトから呼び出して、サーバー上の認証サービスと通信します。

Bb398896.alert_note(ja-jp,VS.90).gifメモ :

独自のサーバー認証サービスを作成できます。詳細については、「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>
Bb398896.alert_note(ja-jp,VS.90).gifメモ :

ブラウザでは Cookie が有効になっている必要があります。認証サービスでは、後続の要求時にユーザーの ID を再確立する認証チケットとして 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 ファイルに追加します。認証されたユーザーにのみアクセスを制限する、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 メソッドを呼び出します。ログアウト後、ページ上部にあるテキストが変更されます。この時点ではブラウザにはフォーム認証 Cookie がないので、Secured フォルダ内のページへのアクセスを試行すると、ログイン ページにリダイレクトされます。

例のコードでは、login メソッドおよび logout メソッドに対し、非同期に実行されるコールバック関数が用意されています。両方のメソッドに対して、失敗コールバック関数を作成することもできます。詳細については、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" 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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://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();

参照

処理手順

方法 : 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 セキュリティのしくみ

メンバシップを使用したユーザーの管理