こんばんは。きわさです。
ASP.NETでWebアプリが作れるそうなので手を出してみました。
簡易的な、必要最低限のログイン処理を作ってみます。
ASP.NET Web アプリケーション MVC のプロジェクトを使用します。
まずModelを。
とりあえず、NameとPasswordのみ。
Models/LoginModels.cs
namespace TestApplication.Models
{
public class LoginViewModel
{
public string Name { get; set; }
public string Password { get; set; }
}
}
次にControllerを。
Controllers/AuthController.cs
using System.Web.Mvc;
using System.Web.Security;
namespace TestApplication.Controllers
{
using Models;
[AllowAnonymous]
public class AuthController : Controller
{
// GET: Auth/Login
public ActionResult Login()
{
return View();
}
// POST: Auth/Login
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
// 簡易版なのでハードコーディングで済ませる
if(model.Name != "test" || model.Password != "test") {
return View(model);
}
// 認証
FormsAuthentication.SetAuthCookie(model.Name, false);
// 今回はログイン後の遷移先は固定
return RedirectToAction("Index", "Home");
}
// GET: Auth/Logout
public ActionResult Logout()
{
// ログアウト
FormsAuthentication.SignOut();
return RedirectToAction("Login");
}
}
}
/Auth/Login にアクセス(GET)でログイン画面を表示、
/Auth/Login にログイン情報をPOSTでログイン処理、
/Auth/Logout にアクセス(GET)でログアウト処理
としています。
[AllowAnonymous] は、認証してない状態でアクセスを許可するためにつけています。
本来なら、ログイン処理のDB参照やパスワードの暗号化、ログイン後の戻り先など、やるべきことは色々ありますが、今回は簡易版なので省略。
次にViewを。
View/Auth/Login.cshtml
@model TestApplication.Models.LoginViewModel
@{
ViewBag.Title = "Login";
}
<h2>Login</h2>
@using (@Html.BeginForm())
{
<table>
<tr>
<th>ユーザー</th>
<td>@Html.TextBoxFor(model => model.Name)</td>
</tr>
<tr>
<th>パスワード</th>
<td>@Html.PasswordFor(model => model.Password)</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="ログイン" />
<td>
</tr>
</table>
}
ユーザーとパスワードの入力用テキストボックスとログインボタンのみです。
バリデーションは省略します。
これでModel、View、Controllerを作成しました。
あと少し。
Web.Configに authentication の3行を追加します。
...
<system.web>
<authentication mode="Forms">
<forms loginUrl="/Auth/Login"/>
</authentication>
...
そしてここにも認証関連の1行を追加します。
App_Start/FilterConfig.cs
using System.Web.Mvc;
namespace TestApplication
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
}
}
}
これにより、アクセスに認証が必要になります。
ログイン関連の画面は [AllowAnonymous] をつけたため、認証なしでもアクセスできます。
