【ASP.NET MVC4】区分追加&WebViewでフォーム認証

はい、世間は夏休みとかいうやつらしいですね。
時間があるからまじめにかく!
とかいいつつ、ただいっつも忘れるからメモなだけーw

ASP.NET MVC4 Webアプリケーションへの区分の追加方法ですよー


Web.configにフォーム認証情報を追加

区分側のWeb.configでなくてプロジェクト側のWeb.configですよー
区分側に書くと構成エラーになっちゃいますよー
エラー見る限り、区分ごときがauthenticationの設定変えんなコラってことみたいですねー
IISかどっかの設定変えればいけるっぽいけど、特に必要に迫られたことがないので割愛。
職業プログラマーなんで、さーせんw

この例だとAdmin/Loginがログインページになりますよー

<!-- 略 -->
<system.web>
<!-- 略 -->
    <authentication mode="Forms">
      <forms loginUrl="Admin/Login" timeout="1440">
      </forms>
    </authentication>
    <!-- 略 -->
  </system.web>
<!-- 略 -->


認証用のフィルター

別になにもやってませんねー。認証済かどうかチェックしてだめだったらUnauthorized返却させるだけですねー

using System.Web.Mvc;

namespace Hoge.Filter
{
    public class WebViewAuthFilterAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var httpContext = filterContext.RequestContext.HttpContext;
            if (!httpContext.User.Identity.IsAuthenticated)
                filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}


区分追加

ソリューションエクスプローラーで追加したいプロジェクト右クリック→追加→区分で「Admin」をいれておk
Areas/Adminができるかと


モデル

Areas/Admin/Modelsにクラスを追加でLoginModelを作成

namespace Hoge.Areas.Admin.Models
{
    public class LoginModel
    {
        public string Id { get; set; }
        public string Password { get; set; }
        public bool RememberMe { get; set; }
    }
}


ログインコントローラー

ソリューションエクスプローラーでAreas/Admin/Controllersを右クリック→追加→コントローラーでLoginControllerを作成
必ずテンプレートで「空の MVC コントローラー」を選択してくださいねー
IDとパスワードのチェックはてきとーですよー
IDとパスワードがおっけーだったらクッキーに認証情報セットしますよー

using System.Web.Mvc;
using System.Web.Security;
using Hoge.Areas.Admin.Models;

namespace Hoge.Areas.Admin.Controllers
{
    public class LoginController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(LoginModel model, string returnUrl)
        {
            if (model.Id.Equals("aiueo") && model.Password.Equals("password"))
            {
                FormsAuthentication.SetAuthCookie(model.Id, model.RememberMe);
                return Redirect(returnUrl == null ? "Top" : returnUrl);
            }

            ModelState.AddModelError(string.Empty, "IDまたはパスワードが違います。");
            return View(model);
        }
    }
}


ログインビュー

Admin/Viewの下にLoginフォルダー作って右クリック→追加→ビューでIndex.cshtml作成
テンプレートエンジンはRazorですよー
@Html.ValidationSummary()って書いとくと、コントローラー側でAddModelErrorした内容を表示してくれますよー

@model Hoge.Areas.Admin.Models.LoginModel

@Html.ValidationSummary()
@using (@Html.BeginForm())
{
<div>
	ログイン<br />
    @Html.TextBoxFor(model => model.Id, new { @placeholder = "ログインID" })<br />
    @Html.PasswordFor(model => model.Password, new { @placeholder = "パスワード" })<br />
    ログイン状態を保存する @Html.CheckBoxFor(model => model.RememberMe)<br />
	<input type="submit" value="ログイン" />
</div>
}


ログイン後のビュー用意

ログインの時みたいにTopControllerとTop/Index.cshtmlを用意
注目は[WebViewAuthFilter]ですねー。

using System.Web.Mvc;
using Hoge.Filter;

namespace Hoge.Areas.Admin.Controllers
{
    [WebViewAuthFilter]
    public class TopController : Controller
    {
        //
        // GET: /Admin/Top/
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
    }
}


<h2>TOP</h2>
とっぷぺーじ
<br />
<a href="/Admin/Logout">ログアウト</a>


ログアウト

LogoutControllerを追加
ログアウトしたらLoginページにリダイレクトしましょーねー

using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Hoge.Areas.Admin.Controllers
{
    public class LogoutController : Controller
    {
        //
        // GET: /Admin/Logout/
        [HttpGet]
        public ActionResult Index()
        {
            if (HttpContext.User.Identity.IsAuthenticated)
                FormsAuthentication.SignOut();

            return Redirect("Login");
        }
    }
}

以上!