次の方法で共有


IIS 7.0 でサンプルの読み取り専用 XML メンバーシップとロール プロバイダーを使用する方法

作成者: Robert McMurray

はじめに

ASP.NET 2.0 がリリースされたとき、Microsoft Developer Network (MSDN) Web サイトは、ASP.NET メンバーシップとロール用の 2 つのサンプル プロバイダーを提供しました。 これらのプロバイダーは、ユーザーとロールの一覧に XML ファイルを使用する読み取り専用プロバイダーであり、次の URL で使用できました:

これらのサンプルは、デモまたはテスト Web サイトで IIS 7.0 以降で使用する場合に適していますが、IIS でのセキュリティの設計方法により、IIS では記述どおりに機能しません。 元の手順では、サンプル メンバーシップ/ロール プロバイダーを Web サイトの App_Code フォルダーに展開することができましたが、IIS では、プロバイダーを展開する前にグローバル アセンブリ キャッシュ (GAC) に登録する必要があります。 これを念頭に置いて、以下のステップでは、読み取り専用 XML プロバイダーをコンパイルして開発システムに展開する手順について説明します。

前提条件

この記事の手順を完了するには、次の項目が必要です:

  1. IIS 7.0 以降を、Windows Vista または Windows Server 2008 コンピューターにインストールする必要があります。
  2. ASP.NET を、IIS のご使用のバージョン用にインストールする必要があります。
  3. IIS 7.0 以降のインターネット インフォメーション サービス マネージャーをインストールする必要があります。
  4. IIS コンピューターに Gacutil.exe が必要です。これは、アセンブリをグローバル アセンブリ キャッシュ (GAC) に追加するために必要です。

手順 1: XML プロバイダー プロジェクトを設定する

この最初の手順では、2 つのプロジェクト (1 つは XML ベースのメンバーシップ プロバイダー用、もう 1 つは XML ベースのロール プロバイダー用) を含むソリューションを Visual Studio で作成します。

  1. Microsoft Visual Studio 2008 を起動します。

  2. [ファイル] メニューの [新規作成][プロジェクト] の順に選択します。

  3. [新しいプロジェクト] ダイアログで次の操作を行います。

    • プロジェクトの種類として [Visual C#] を選択します。
    • テンプレートとして [クラス ライブラリ] を選択します。
    • プロジェクトの名前として「ReadOnlyXmlMembershipProvider」と入力します。
    • ソリューションの名前として「ReadOnlyXmlProviders」と入力します。
    • OK をクリックします。
  4. ReadOnlyXmlMembershipProvider プロジェクトから Class1.cs ファイルを削除します:

    • ソリューション エクスプローラーで、ReadOnlyXmlMembershipProvider プロジェクトの Class1.cs ファイルを右クリックし、[削除] をクリックします。
    • クラスを完全に削除するように求められたら、[OK] をクリックします。
  5. System.Configuration ライブラリへの参照パスを追加します:

    • ソリューション エクスプローラーで、ReadOnlyXmlMembershipProvider プロジェクトを右クリックし、[参照の追加...] をクリックします。
    • [.NET] タブをクリックします。
    • アセンブリの一覧で [System.Configuration] を選択します。
    • OK をクリックします。
  6. System.Web ライブラリへの参照パスを追加します:

    • ソリューション エクスプローラーで、ReadOnlyXmlMembershipProvider プロジェクトを右クリックし、[参照の追加...] をクリックします。
    • [.NET] タブをクリックします。
    • アセンブリの一覧で [System.Web] を選択します。
    • OK をクリックします。
  7. プロジェクトに厳密な名前のキーを追加します:

    • ソリューション エクスプローラーで、ReadOnlyXmlRoleProvider プロジェクトを右クリックし、[プロパティ] をクリックします。
    • [署名] タブをクリックします。
    • [アセンブリの署名] チェック ボックスをオンにします。
    • 厳密なキー名のドロップダウン ボックスから <[新規...]> を選択します。
    • キー ファイル名として「ReadOnlyXmlMembershipProviderKey」と入力します。
    • 必要に応じて、キー ファイルのパスワードを入力します。それ以外の場合は、[パスワードでキー ファイルを保護する] ボックスをオフにします。
    • OK をクリックします。
  8. (省略可能) カスタム ビルド イベントを追加して、DLL を GAC に自動的に登録します:

    • ソリューション エクスプローラーで、ReadOnlyXmlRoleProvider プロジェクトを右クリックし、[プロパティ] をクリックします。

    • [ビルド イベント] タブをクリックします。

    • [ビルド後に実行するコマンド ライン] ボックスに、次のように入力します:

      call "%VS90COMNTOOLS%\vsvars32.bat">nul
      gacutil.exe /if "$(TargetPath)"
      
  9. 2 番目のプロジェクトをソリューションに追加します:

    • [ファイル][追加][新しいプロジェクト...] の順にクリックします。
    • プロジェクトの種類として [Visual C#] を選択します。
    • テンプレートとして [クラス ライブラリ] を選択します。
    • プロジェクトの名前として「ReadOnlyXmlRoleProvider」と入力します。
    • OK をクリックします。
  10. ReadOnlyXmlRoleProvider プロジェクトから Class1.cs ファイルを削除します:

    • ソリューション エクスプローラーで、ReadOnlyXmlRoleProvider プロジェクトの Class1.cs ファイルを右クリックし、[削除] をクリックします。
    • クラスを完全に削除するように求められたら、[OK] をクリックします。
  11. System.Configuration ライブラリへの参照パスを追加します:

    • ソリューション エクスプローラーで、ReadOnlyXmlRoleProvider プロジェクトを右クリックし、[参照の追加...] をクリックします。
    • [.NET] タブをクリックします。
    • アセンブリの一覧で [System.Configuration] を選択します。
    • OK をクリックします。
  12. System.Web ライブラリへの参照パスを追加します:

    • ソリューション エクスプローラーで、ReadOnlyXmlRoleProvider プロジェクトを右クリックし、[参照の追加...] をクリックします。
    • [.NET] タブをクリックします。
    • アセンブリの一覧で [System.Web] を選択します。
    • OK をクリックします。
  13. プロジェクトに厳密な名前のキーを追加します:

    • ソリューション エクスプローラーで、ReadOnlyXmlRoleProvider プロジェクトを右クリックし、[プロパティ] をクリックします。
    • [署名] タブをクリックします。
    • [アセンブリの署名] チェック ボックスをオンにします。
    • 厳密なキー名のドロップダウン ボックスから <[新規...]> を選択します。
    • キー ファイル名として「ReadOnlyXmlRoleProvider」と入力します。
    • 必要に応じて、キー ファイルのパスワードを入力します。それ以外の場合は、[パスワードでキー ファイルを保護する] ボックスをオフにします。
    • OK をクリックします。
  14. (省略可能) カスタム ビルド イベントを追加して、DLL を GAC に自動的に登録します:

    • ソリューション エクスプローラーで、ReadOnlyXmlRoleProvider プロジェクトを右クリックし、[プロパティ] をクリックします。

    • [ビルド イベント] タブをクリックします。

    • [ビルド後に実行するコマンド ライン] ボックスに、次のように入力します:

      call "%VS90COMNTOOLS%\vsvars32.bat">nul
      gacutil.exe /if "$(TargetPath)"
      
  15. ソリューションを保存します。

手順 2: プロジェクトのプロバイダー クラスを追加する

この 2 番目の手順では、XML ベースのメンバーシップとロール プロバイダーのクラスを作成します。 これらのクラスのコードは、MSDN の「メンバーシップ プロバイダー」と「ロール プロバイダー」に関するトピックからコピーされます。

  1. ReadOnlyXmlMembershipProvider プロジェクトに新しいクラスを追加します:

    • ソリューション エクスプローラーで、ReadOnlyXmlMembershipProvider プロジェクトを右クリックし、[追加][クラス...] の順にクリックします。

    • クラスに「ReadOnlyXmlMembershipProvider.cs」という名前を付けます。

    • 追加をクリックします。

    • 既存のコードを削除します。

    • メンバーシップ プロバイダー」トピックの次のサンプル コードをエディターに貼り付けます:

      using System;
      using System.Xml;
      using System.Collections.Generic;
      using System.Collections.Specialized;
      using System.Configuration.Provider;
      using System.Web.Security;
      using System.Web.Hosting;
      using System.Web.Management;
      using System.Security.Permissions;
      using System.Web;
      
      public class ReadOnlyXmlMembershipProvider : MembershipProvider
      {
         private Dictionary<string, MembershipUser> _Users;
         private string _XmlFileName;
      
         // MembershipProvider Properties
         public override string ApplicationName
         {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
         }
      
         public override bool EnablePasswordRetrieval
         {
            get { return false; }
         }
      
         public override bool EnablePasswordReset
         {
            get { return false; }
         }
      
         public override int MaxInvalidPasswordAttempts
         {
            get { throw new NotSupportedException(); }
         }
      
         public override int MinRequiredNonAlphanumericCharacters
         {
            get { throw new NotSupportedException(); }
         }
      
         public override int MinRequiredPasswordLength
         {
            get { throw new NotSupportedException(); }
         }
      
         public override int PasswordAttemptWindow
         {
            get { throw new NotSupportedException(); }
         }
      
         public override MembershipPasswordFormat PasswordFormat
         {
            get { throw new NotSupportedException(); }
         }
      
         public override string PasswordStrengthRegularExpression
         {
            get { throw new NotSupportedException(); }
         }
      
         public override bool RequiresQuestionAndAnswer
         {
            get { throw new NotSupportedException(); }
         }
      
         public override bool RequiresUniqueEmail
         {
            get { throw new NotSupportedException(); }
         }
      
         // MembershipProvider Methods
         public override void Initialize(string name,
            NameValueCollection config)
         {
            // Verify that config isn't null
            if (config == null)
               throw new ArgumentNullException("config");
            // Assign the provider a default name if it doesn't have one
            if (String.IsNullOrEmpty(name))
               name = "ReadOnlyXmlMembershipProvider";
            // Add a default "description" attribute to config if the
            // attribute doesn't exist or is empty
            if (string.IsNullOrEmpty(config["description"]))
            {
               config.Remove("description");
               config.Add("description",
                  "Read-only XML membership provider");
            }
            // Call the base class's Initialize method
            base.Initialize(name, config);
            // Initialize _XmlFileName and make sure the path
            // is app-relative
            string path = config["xmlFileName"];
            if (String.IsNullOrEmpty(path))
               path = "~/App_Data/Users.xml";
            if (!VirtualPathUtility.IsAppRelative(path))
               throw new ArgumentException
                  ("xmlFileName must be app-relative");
            string fullyQualifiedPath = VirtualPathUtility.Combine
               (VirtualPathUtility.AppendTrailingSlash
               (HttpRuntime.AppDomainAppVirtualPath), path);
            _XmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath);
            config.Remove("xmlFileName");
            // Make sure we have permission to read the XML data source and
            // throw an exception if we don't
            FileIOPermission permission =
               new FileIOPermission(FileIOPermissionAccess.Read,
                  _XmlFileName);
            permission.Demand();
            // Throw an exception if unrecognized attributes remain
            if (config.Count > 0)
            {
               string attr = config.GetKey(0);
               if (!String.IsNullOrEmpty(attr))
                  throw new ProviderException
                      ("Unrecognized attribute: " + attr);
            }
         }
      
         public override bool ValidateUser(string username, string password)
         {
            // Validate input parameters
            if (String.IsNullOrEmpty(username) ||
               String.IsNullOrEmpty(password))
                  return false;
            try
            {
               // Make sure the data source has been loaded
               ReadMembershipDataStore();
               // Validate the user name and password
               MembershipUser user;
               if (_Users.TryGetValue(username, out user))
               {
                  if (user.Comment == password) // Case-sensitive
                  {
                     // NOTE: A read/write membership provider
                     // would update the user's LastLoginDate here.
                     // A fully featured provider would also fire
                     // an AuditMembershipAuthenticationSuccess
                     // Web event
                     return true;
                  }
               }
               // NOTE: A fully featured membership provider would
               // fire an AuditMembershipAuthenticationFailure
               // Web event here
               return false;
            }
            catch (Exception)
            {
               return false;
            }
         }
      
         public override MembershipUser GetUser(string username,
            bool userIsOnline)
         {
            // Note: This implementation ignores userIsOnline
            // Validate input parameters
               if (String.IsNullOrEmpty(username))
               return null;
            // Make sure the data source has been loaded
            ReadMembershipDataStore();
            // Retrieve the user from the data source
            MembershipUser user;
            if (_Users.TryGetValue(username, out user))
               return user;
            return null;
         }
      
         public override MembershipUserCollection GetAllUsers(int pageIndex,
            int pageSize, out int totalRecords)
         {
            // Note: This implementation ignores pageIndex and pageSize,
            // and it doesn't sort the MembershipUser objects returned
            // Make sure the data source has been loaded
            ReadMembershipDataStore();
            MembershipUserCollection users =
               new MembershipUserCollection();
            foreach (KeyValuePair<string, MembershipUser> pair in _Users)
               users.Add(pair.Value);
            totalRecords = users.Count;
            return users;
         }
      
         public override int GetNumberOfUsersOnline()
         {
            throw new NotSupportedException();
         }
      
         public override bool ChangePassword(string username,
            string oldPassword, string newPassword)
         {
            throw new NotSupportedException();
         }
      
         public override bool
            ChangePasswordQuestionAndAnswer(string username,
            string password, string newPasswordQuestion,
            string newPasswordAnswer)
         {
            throw new NotSupportedException();
         }
      
         public override MembershipUser CreateUser(string username,
            string password, string email, string passwordQuestion,
            string passwordAnswer, bool isApproved, object providerUserKey,
            out MembershipCreateStatus status)
         {
            throw new NotSupportedException();
         }
      
         public override bool DeleteUser(string username,
            bool deleteAllRelatedData)
         {
            throw new NotSupportedException();
         }
      
         public override MembershipUserCollection
            FindUsersByEmail(string emailToMatch, int pageIndex,
            int pageSize, out int totalRecords)
         {
            throw new NotSupportedException();
         }
      
         public override MembershipUserCollection
            FindUsersByName(string usernameToMatch, int pageIndex,
            int pageSize, out int totalRecords)
         {
            throw new NotSupportedException();
         }
      
         public override string GetPassword(string username, string answer)
         {
            throw new NotSupportedException();
         }
      
         public override MembershipUser GetUser(object providerUserKey,
            bool userIsOnline)
         {
            throw new NotSupportedException();
         }
      
         public override string GetUserNameByEmail(string email)
         {
            throw new NotSupportedException();
         }
      
         public override string ResetPassword(string username,
            string answer)
         {
            throw new NotSupportedException();
         }
      
         public override bool UnlockUser(string userName)
         {
            throw new NotSupportedException();
         }
      
         public override void UpdateUser(MembershipUser user)
         {
            throw new NotSupportedException();
         }
      
         // Helper method
         private void ReadMembershipDataStore()
         {
            lock (this)
            {
               if (_Users == null)
               {
                  _Users = new Dictionary<string, MembershipUser>
                     (16, StringComparer.InvariantCultureIgnoreCase);
                  XmlDocument doc = new XmlDocument();
                  doc.Load(_XmlFileName);
                  XmlNodeList nodes = doc.GetElementsByTagName("User");
                  foreach (XmlNode node in nodes)
                  {
                     MembershipUser user = new MembershipUser(
                        Name,                       // Provider name
                        node["UserName"].InnerText, // Username
                        null,                       // providerUserKey
                        node["EMail"].InnerText,    // Email
                        String.Empty,               // passwordQuestion
                        node["Password"].InnerText, // Comment
                        true,                       // isApproved
                        false,                      // isLockedOut
                        DateTime.Now,               // creationDate
                        DateTime.Now,               // lastLoginDate
                        DateTime.Now,               // lastActivityDate
                        DateTime.Now,               // lastPasswordChangedDate
                        new DateTime(1980, 1, 1)    // lastLockoutDate
                     );
                     _Users.Add(user.UserName, user);
                  }
               }
            }
         }
      }
      
  2. ReadOnlyXmlRoleProvider プロジェクトに新しいクラスを追加します:

    • ソリューション エクスプローラーで、ReadOnlyXmlRoleProvider プロジェクトを右クリックし、[追加][クラス...] の順にクリックします。

    • クラスに「ReadOnlyXmlRoleProvider.cs」という名前を付けます。

    • 追加をクリックします。

    • 既存のコードを削除します。

    • ロール プロバイダー」トピックの次のサンプル コードをエディターに貼り付けます:

      using System;
      using System.Web.Security;
      using System.Collections.Generic;
      using System.Collections.Specialized;
      using System.Configuration.Provider;
      using System.Web.Hosting;
      using System.Xml;
      using System.Security.Permissions;
      using System.Web;
      
      public class ReadOnlyXmlRoleProvider : RoleProvider
      {
         private Dictionary<string, string[]> _UsersAndRoles =
         new Dictionary<string, string[]>(16,
         StringComparer.InvariantCultureIgnoreCase);
      
         private Dictionary<string, string[]> _RolesAndUsers =
            new Dictionary<string, string[]>(16,
            StringComparer.InvariantCultureIgnoreCase);
      
         private string _XmlFileName;
      
         // RoleProvider properties
         public override string ApplicationName
         {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
         }
      
         // RoleProvider methods
         public override void Initialize(string name,
         NameValueCollection config)
         {
            // Verify that config isn't null
            if (config == null)
               throw new ArgumentNullException("config");
            // Assign the provider a default name if it doesn't have one
            if (String.IsNullOrEmpty(name))
               name = "ReadOnlyXmlRoleProvider";
            // Add a default "description" attribute to config if the
            // attribute doesn't exist or is empty
            if (string.IsNullOrEmpty(config["description"]))
            {
               config.Remove("description");
               config.Add("description", "Read-only XML role provider");
            }
            // Call the base class's Initialize method
            base.Initialize(name, config);
            // Initialize _XmlFileName and make sure the path
            // is app-relative
            string path = config["xmlFileName"];
            if (String.IsNullOrEmpty(path))
               path = "~/App_Data/Users.xml";
            if (!VirtualPathUtility.IsAppRelative(path))
               throw new ArgumentException
                  ("xmlFileName must be app-relative");
            string fullyQualifiedPath = VirtualPathUtility.Combine
               (VirtualPathUtility.AppendTrailingSlash
               (HttpRuntime.AppDomainAppVirtualPath), path);
            _XmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath);
            config.Remove("xmlFileName");
            // Make sure we have permission to read the XML data source and
            // throw an exception if we don't
            FileIOPermission permission =
               new FileIOPermission(FileIOPermissionAccess.Read,
                  _XmlFileName);
            permission.Demand();
            // Throw an exception if unrecognized attributes remain
            if (config.Count > 0)
            {
               string attr = config.GetKey(0);
               if (!String.IsNullOrEmpty(attr))
                  throw new ProviderException
                     ("Unrecognized attribute: " + attr);
            }
            // Read the role data source. NOTE: Unlike
            // ReadOnlyXmlMembershipProvider, this provider can
            // read the data source at this point because Read-
            // RoleDataStore doesn't call into the role manager
            ReadRoleDataStore();
         }
      
         public override bool IsUserInRole(string username, string roleName)
         {
            // Validate input parameters
            if (username == null || roleName == null)
               throw new ArgumentNullException();
            if (username == String.Empty || roleName == string.Empty)
               throw new ArgumentException();
            // Make sure the user name and role name are valid
            if (!_UsersAndRoles.ContainsKey(username))
               throw new ProviderException("Invalid user name");
            if (!_RolesAndUsers.ContainsKey(roleName))
               throw new ProviderException("Invalid role name");
            // Determine whether the user is in the specified role 
            string[] roles = _UsersAndRoles[username];
            foreach (string role in roles)
            {
               if (String.Compare(role, roleName, true) == 0)
                  return true;
            }
            return false;
         }
      
         public override string[] GetRolesForUser(string username)
         {
            // Validate input parameters
            if (username == null)
               throw new ArgumentNullException();
            if (username == string.Empty)
               throw new ArgumentException();
            // Make sure the user name is valid
            string[] roles;
            if (!_UsersAndRoles.TryGetValue(username, out roles))
               throw new ProviderException("Invalid user name");
            // Return role names
            return roles;
         }
      
         public override string[] GetUsersInRole(string roleName)
         {
            // Validate input parameters
            if (roleName == null)
               throw new ArgumentNullException();
            if (roleName == string.Empty)
            throw new ArgumentException();
            // Make sure the role name is valid
            string[] users;
            if (!_RolesAndUsers.TryGetValue(roleName, out users))
               throw new ProviderException("Invalid role name");
            // Return user names
            return users;
         }
      
         public override string[] GetAllRoles()
         {
            int i = 0;
            string[] roles = new string[_RolesAndUsers.Count];
            foreach (KeyValuePair<string, string[]> pair in _RolesAndUsers)
               roles[i++] = pair.Key;
            return roles;
         }
      
         public override bool RoleExists(string roleName)
         {
            // Validate input parameters
            if (roleName == null)
               throw new ArgumentNullException();
            if (roleName == string.Empty)
               throw new ArgumentException();
            // Determine whether the role exists
            return _RolesAndUsers.ContainsKey(roleName);
         }
      
         public override void CreateRole(string roleName)
         {
            throw new NotSupportedException();
         }
      
         public override bool DeleteRole(string roleName,
            bool throwOnPopulatedRole)
         {
            throw new NotSupportedException();
         }
      
         public override void AddUsersToRoles(string[] usernames,
            string[] roleNames)
         {
            throw new NotSupportedException();
         }
      
         public override string[] FindUsersInRole(string roleName,
            string usernameToMatch)
         {
            throw new NotSupportedException();
         }
      
         public override void RemoveUsersFromRoles(string[] usernames,
            string[] roleNames)
         {
            throw new NotSupportedException();
         }
      
         // Helper method
         private void ReadRoleDataStore()
         {
            XmlDocument doc = new XmlDocument();
            doc.Load(_XmlFileName);
            XmlNodeList nodes = doc.GetElementsByTagName("User");
            foreach (XmlNode node in nodes)
            {
               if (node["UserName"] == null)
                  throw new ProviderException
                     ("Missing UserName element");
               string user = node["UserName"].InnerText;
               if (String.IsNullOrEmpty(user))
                  throw new ProviderException("Empty UserName element");
               if (node["Roles"] == null ||
                  String.IsNullOrEmpty(node["Roles"].InnerText))
                     _UsersAndRoles.Add(user, new string[0]);
               else
               {
                  string[] roles = node["Roles"].InnerText.Split(',');
                  // Add the role names to _UsersAndRoles and
                  // key them by user name
                  _UsersAndRoles.Add(user, roles);
                  foreach (string role in roles)
                  {
                     // Add the user name to _RolesAndUsers and
                     // key it by role names
                     string[] users1;
                     if (_RolesAndUsers.TryGetValue(role, out users1))
                     {
                        string[] users2 =
                           new string[users1.Length + 1];
                        users1.CopyTo(users2, 0);
                        users2[users1.Length] = user;
                        _RolesAndUsers.Remove(role);
                        _RolesAndUsers.Add(role, users2);
                     }
                     else
                        _RolesAndUsers.Add(role,
                     new string[] { user });
                  }
               }
            }
         }
      }
      
  3. 両方のプロジェクトを保存してコンパイルします。

Note

オプションの手順を使用してアセンブリを GAC に登録しなかった場合は、手動でアセンブリを IIS コンピューターにコピーし、Gacutil.exe ツールを使用してアセンブリを GAC に追加する必要があります。 詳細については、Microsoft の MSDN Web サイトで次のトピックを参照してください:

手順 3: IIS にプロバイダーを追加する

この 3 番目の手順では、メンバーシップとロール プロバイダーのアセンブリ情報を決定し、その情報を IIS の信頼されたプロバイダーの一覧に追加します。

  1. 両方のプロバイダーのアセンブリ情報を決定します:

    • Windows エクスプローラーで C:\Windows\assembly パスを開きます。C: はオペレーティング システム ドライブです。
    • ReadOnlyXmlMembershipProvider アセンブリと ReadOnlyXmlRoleProvider アセンブリを見つけます。
    • それぞれのアセンブリを右クリックし、[プロパティ] をクリックします。
    • Culture の値 (例: Neutral) をコピーします。
    • Version 番号 (例: 1.0.0.0) をコピーします。
    • Public Key Token の値 (例: 426f62526f636b73) をコピーします。
    • [キャンセル] をクリックします。
  2. IIS の信頼できるプロバイダーの一覧に XML プロバイダーを追加します:

    • Administration.config ファイルを編集用に開きます。

      Note

      このファイルは %WinDir%\System32\Inetsrv\Config フォルダーにあります。

    • 次の構文を使用して、前の手順のアセンブリ プロパティを持つプロバイダーを <trustedProviders> セクションに追加します:

      <add type="ReadOnlyXmlMembershipProvider, ReadOnlyXmlMembershipProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=426f62526f636b73" />
      
      <add type="ReadOnlyXmlRoleProvider, ReadOnlyXmlRoleProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=426f62526f636b73" />
      
    • Administration.config ファイルを保存して閉じます。

手順 4: XML プロバイダーを使用してフォーム認証用のサイトを構成する

この 4 番目の手順では、XML ベースのメンバーシップとロール プロバイダーでフォーム認証を使用するように Web サイトを構成します。そのために、Web サイト用の Web.config ファイルを手動で作成し、ユーザーのリストを含む XML ファイルを Web サイトの App_Data フォルダーに追加し、フォーム認証要求を処理する Login.aspx ページを Web サイトに追加します。

  1. メンバーシップ ユーザーとロール用の XML ファイルを作成します:

    • テキスト エディターに次のコードを貼り付けます:

      <Users>
         <User>
            <UserName>Bob</UserName>
            <Password>contoso!</Password>
            <EMail>bob@contoso.com</EMail>
            <Roles>Members</Roles>
         </User>
         <User>
            <UserName>Alice</UserName>
            <Password>contoso!</Password>
            <EMail>alice@contoso.com</EMail>
            <Roles>Members,Administrators</Roles>
         </User>
      </Users>
      
    • コードを "Users.xml" として Web サイトの App_Data フォルダーに保存します。

  2. Web サイト用の Login.aspx ファイルを作成します:

    • テキスト エディターに次のコードを貼り付けます:

      <%@ Page Language="C#" %>
      <%@ Import Namespace="System.ComponentModel" %>
      <html>
      <head runat="server">
      <title>Login Page</title>
      </head>
      <body>
         <form id="form1" runat="server">
            <asp:Login id="Login1" runat="server"
                  BorderStyle="Solid"
                  BackColor="#ffffcc"
                  BorderWidth="1px"
                  BorderColor="#cccc99"
                  Font-Size="10pt"
                  Font-Names="Verdana">
               <TitleTextStyle Font-Bold="True"
                  ForeColor="#ffffff"
                  BackColor="#666666"/>
            </asp:Login>
         </form>
      </body>
      </html>
      
    • コードを "Login.aspx" として Web サイトのルートに保存します。

  3. Web サイト用の Web.config ファイルを作成します:

    • テキスト エディターに次のコードを貼り付けます:

      <configuration>
         <system.web>
            <!-- Add the read-only XML membership provider and set it as the default. -->
            <membership defaultProvider="AspNetReadOnlyXmlMembershipProvider">
               <providers>
                  <add name="AspNetReadOnlyXmlMembershipProvider"
                     type="ReadOnlyXmlMembershipProvider, ReadOnlyXmlMembershipProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=91454274822e8111"
                     description="Read-only XML membership provider"
                     xmlFileName="~/App_Data/Users.xml" />
               </providers>
            </membership>
            <!-- Add the read-only XML role provider and set it as the default. -->
            <roleManager enabled="true" defaultProvider="AspNetReadOnlyXmlRoleProvider">
               <providers>
                  <add name="AspNetReadOnlyXmlRoleProvider"
                     type="ReadOnlyXmlRoleProvider, ReadOnlyXmlRoleProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a9c0f8ad39898a3c"
                     description="Read-only XML role provider"
                     xmlFileName="~/App_Data/Users.xml" />
               </providers>
            </roleManager>
            <!-- Set the authentication mode to forms authentication. -->
            <authentication mode="Forms" />
         </system.web>
         <system.webServer>
            <!-- Configure the authentication and roles modules for all content. -->
            <modules>
               <remove name="RoleManager" />
               <remove name="DefaultAuthentication" />
               <remove name="FormsAuthentication" />
               <add name="FormsAuthentication"
                  type="System.Web.Security.FormsAuthenticationModule"
                  preCondition="" />
               <add name="DefaultAuthentication"
                  type="System.Web.Security.DefaultAuthenticationModule"
                  preCondition="" />
               <add name="RoleManager"
                  type="System.Web.Security.RoleManagerModule"
                  preCondition="" />
            </modules>
            <!-- Add authorization rules for membership roles. -->
            <security>
               <authorization>
                  <clear />
                  <add accessType="Allow" roles="Administrators" />
                  <add accessType="Allow" roles="Members" />
               </authorization>
            </security>
         </system.webServer>
      </configuration>
      

      Note

      web.config の <providers> セクションの PublicKeyToken の値は、Administration.config ファイルの <trustedProviders> セクションの PublicKeyToken の値と一致している必要があります。

    • コードを "Web.config" として Web サイトのルートに保存します。

まとめ

このチュートリアルでは、以下の作業を完了しました:

  • 読み取り専用 XML メンバーシップとロール プロバイダー用に、Visual Studio 2008 で 2 つのクラス プロジェクトを設定しました。
  • プロジェクトをコンパイルし、グローバル アセンブリ キャッシュに追加しました。
  • IIS の信頼されたプロバイダーとして XML メンバーシップとロール プロバイダーを追加しました。
  • XML プロバイダーを使用してフォーム認証用の Web サイトを構成しました。