Asp.net-wp-security

提供:Dev Guides
移動先:案内検索

ASP.NET WP-セキュリティ

この章では、一部のページがログインしたユーザーのみが利用できるように、*ウェブサイトを保護する*方法について説明します。 Webサイトを保護するには、ユーザーがログインできるようにWebサイトを作成します。 Webサイトを保護することは、多くの理由で役立ちます。

  • サイトには、メンバーのみが利用できるページがある場合があります。
  • フィードバックを送信したり、ウェブサイトにコメントを残したりできるように、ユーザーにログインを要求する場合があります。
  • ユーザーがログインしていない場合でも、すべてのページではなく、いくつかのページを閲覧できます。
  • ログインしていないユーザーは、*匿名ユーザー*と呼ばれます。

認証でウェブサイトを保護する方法は?

ユーザーは最初にWebサイトに登録する必要があり、その後サイトにログインできます。 Webサイトに登録するには、ユーザーは、ユーザーが本人であることを確認するためのユーザー名とメールアドレス、パスワードが必要です。 ログインしてユーザーのIDを確認するこのプロセスは、*認証*と呼ばれます。

*WebMatrix* は、 *Starter Site* と呼ばれる組み込みテンプレートを提供して、次のプロパティを含むWebサイトを作成します。
  • ユーザーのユーザー名とパスワードを保存できるデータベース。
  • ユーザーが登録できる登録ページ。
  • ログイン/ログアウトページ。
  • パスワードの回復とリセットのページ。

新しいスターターサイトを作成して、簡単な例を見てみましょう。

テンプレートからのサイト

[サイト名]フィールドに SecurityDemo と入力し、[次へ]をクリックします。 これにより、必要なパッケージがインストールおよび構成されます。

インストールが完了したら、アプリケーションを実行してみましょう。次のWebページが表示されます。

ホームページ

ご覧のとおり、ページの右上に*登録*と*ログイン*の2つのボタンがあります。

[登録]リンクをクリックすると、次の情報を入力して登録できる次のWebページが表示されます。

登録

以下は、サイトのAccountフォルダーの下にある実装 Register.cshtml ファイルです。

*@* バンドリングを使用している場合は、このセクションを削除してください *@*
@section Scripts {
   <script src = "~/Scripts/jquery.validate.min.js"></script>
   <script src = "~/Scripts/jquery.validate.unobtrusive.min.js"></script>
}
@{
   Layout = "~/_SiteLayout.cshtml";
   Page.Title = "Register";

  //Initialize general page variables
   var email = "";
   var password = "";
   var confirmPassword = "";

  //Setup validation
   Validation.RequireField("email", "You must specify an email address.");
   Validation.RequireField("password", "Password cannot be blank.");
   Validation.Add("confirmPassword",
   Validator.EqualsTo("password", "Password and confirmation password do not match."));
   Validation.Add("password",
      Validator.StringLength(
         maxLength: Int32.MaxValue,
         minLength: 6,
         errorMessage: "Password must be at least 6 characters"));

  //If this is a POST request, validate and process data
   if (IsPost) {
      AntiForgery.Validate();
      email = Request.Form["email"];
      password = Request.Form["password"];
      confirmPassword = Request.Form["confirmPassword"];

     //Validate the user's captcha answer
     //if (!ReCaptcha.Validate("PRIVATE_KEY")) {
        //ModelState.AddError("recaptcha", "Captcha response was not correct");
     //}

     //If all information is valid, create a new account
      if (Validation.IsValid()) {
        //Insert a new user into the database
         var db = Database.Open("StarterSite");

        //Check if user already exists
         var user = db.QuerySingle("SELECT Email FROM UserProfile WHERE LOWER(Email) =
            LOWER(@0)", email);

         if (user == null) {
           //Insert email into the profile table
            db.Execute("INSERT INTO UserProfile (Email) VALUES (@0)", email);
           //Create and associate a new entry in the membership database.
           //If successful, continue processing the request

            try {
               bool requireEmailConfirmation = !WebMail.SmtpServer.IsEmpty();
               var token = WebSecurity.CreateAccount(email, password,
                  requireEmailConfirmation);

               if (requireEmailConfirmation) {
                  var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer,
                     UriFormat.Unescaped);
                  var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute
                     ("~/Account/Confirm?confirmationCode = "
                     + HttpUtility.UrlEncode(token));
                  WebMail.Send(
                     to: email,
                     subject: "Please confirm your account",
                     body: "Your confirmation code is: " + token + ".
                     Visit <a href = \"" + confirmationUrl + "\">" +
                     confirmationUrl + "</a> to activate your account."
                  );
               }

               if (requireEmailConfirmation) {
                 //Thank the user for registering and let them know an
                     email is on its way
                  Response.Redirect("~/Account/Thanks");
               } else {
                 //Navigate back to the homepage and exit
                  WebSecurity.Login(email, password);
                  Response.Redirect("~/");
               }
            }catch (System.Web.Security.MembershipCreateUserException e) {
               ModelState.AddFormError(e.Message);
            }
         } else {
           //User already exists
            ModelState.AddFormError("Email address is already in use.");
         }
      }
   }
}

<hgroup class = "title">
   <h1>@Page.Title.</h1>
   <h2>Create a new account.</h2>
</hgroup>

<form method = "post">
   @AntiForgery.GetHtml()
   @ *If at least one validation error exists, notify the user* @
   @Html.ValidationSummary("Account creation was unsuccessful.
      Please correct the errors and try again.",
      excludeFieldErrors: true, htmlAttributes: null)

   <fieldset>
      <legend>Registration Form</legend>
      <ol>
         <li class = "email">
            <label for = "email" @if(!ModelState.IsValidField("email")){
               <text>class = "error-label"</text>}>Email address</label>
            <input type = "text" id = "email" name = "email" value = "@email"
               @Validation.For("email")/>

            @ *Write any email validation errors to the page* @
            @Html.ValidationMessage("email")
         </li>

         <li class = "password">
            <label for = "password" @if(!ModelState.IsValidField("password")) {<text>
               class = "error-label"</text>}>Password</label>
            <input type = "password" id = "password" name = "password"
               @Validation.For("password")/>

            @ *Write any password validation errors to the page* @
            @Html.ValidationMessage("password")
         </li>

         <li class = "confirm-password">
            <label for = "confirmPassword"
               @if(!ModelState.IsValidField("confirmPassword"))
               {<text>class = "error-label"</text>}>Confirm password</label>
            <input type = "password" id = "confirmPassword" name = "confirmPassword"
               @Validation.For("confirmPassword")/>

            @ *Write any password validation errors to the page* @
            @Html.ValidationMessage("confirmPassword")
         </li>

         <li class = "recaptcha">
            <div class = "message-info">
               <p>
                  To enable CAPTCHA verification, <a href =
                  "http://go.microsoft.com/fwlink/?LinkId=204140">install the
                  ASP.NET Web Helpers Library</a> and uncomment ReCaptcha.GetHtml
                  and replace 'PUBLIC_KEY' with your public key. At the top of this
                  page, uncomment ReCaptcha. Validate and replace 'PRIVATE_KEY' with
                  your private key.Register for reCAPTCHA keys at <a href =
                  "http://recaptcha.net"> reCAPTCHA.net</a>.
               </p>
            </div>
            @*
               @ReCaptcha.GetHtml("PUBLIC_KEY", theme: "white")
               @Html.ValidationMessage("recaptcha")
            *@
         </li>
      </ol>
      <input type = "submit" value = "Register"/>

   </fieldset>
</form>

[登録]ボタンをクリックすると、ホームページが再び表示されますが、メールIDを記載してログインしていることがわかります。

ロゴ

メンバー専用ページを作成

ウェブサイトでは、*メンバーのみ*のみがアクセスできるページが必要になります。 ASP.NETでは、ログインしたメンバーのみがアクセスできるようにページを構成できます。 通常、*匿名ユーザー*が*メンバー専用ページ*にアクセスしようとすると、*ログインページ*にリダイレクトされます。

  • Aboutページ*を変更する簡単な例を見てみましょう。 ユーザーがログインすると、ユーザーはこのページにアクセスできます。そうしないと、ユーザーはログインページにリダイレクトされます。 About.cshtml ファイルの次のコードを置き換えましょう。
@if (!WebSecurity.IsAuthenticated) {
   Response.Redirect("~/Account/Login");
}
@{
   Layout = "~/_SiteLayout.cshtml";
   Page.Title = "About My Site";
}

<hgroup class = "title">
   <h1>@Page.Title.</h1>
   <h2>Your app description page.</h2>
</hgroup>

<article>
   <p>Use this area to provide additional information.</p>
   <p>Use this area to provide additional information.</p>
   <p>Use this area to provide additional information.</p>
</article>

<aside>
   <h3>Aside Title</h3>
   <p>Use this area to provide additional information.</p>

   <ul>
      <li><a href = "~/">Home</a></li>
      <li><a href = "~/About">About</a></li>
      <li><a href = "~/Contact">Contact</a></li>
   </ul>

</aside>

アプリケーションを実行してみましょう。次のホームページが表示されます。

ログインページ

ユーザーは現在ログインしていないため、[About]リンクをクリックすると、次のスクリーンショットに示すようにログインページに移動することがわかります。

ローカルアカウントを使用

資格情報を入力しましょう。

ログインローカルアカウント

[ログイン]をクリックすると、ホームページが表示されます。

[About]リンクをクリックすると、次のスクリーンショットに示すように、[About]ページにアクセスできるようになります。

個人用サイトについて