C#
定石2: Forms認証—フォームログイン+ Cookie
出典: 業務イントラの認証 — Windows認証 / Forms認証 / Cookie の使い分けで業務SE が踏む選択 — 定石2: Forms認証—フォームログイン+ Cookie
// ✅定石2: Login ActionでのCookie発行
using System.Web.Security;
public class AccountController : Controller
{
[AllowAnonymous] //認証前でもアクセス可
public ActionResult Login()=> View();
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginVm model, string returnUrl)
{
//自前DBでパスワード検証(ハッシュ化済み)
var user = _userService.Authenticate(model.UserId, model.Password);
if (user == null)
{
ModelState.AddModelError("", "IDまたはパスワードが違います");
return View(model);
}
// Cookie発行(Forms認証)
FormsAuthentication.SetAuthCookie(user.UserId, model.RememberMe);
return Redirect(returnUrl ?? "/");
}
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login");
}
}
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
Source収録記事
この snippet は記事の「定石2: Forms認証—フォームログイン+ Cookie」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
4 件// ✅定石1: Action内でユーザー名取得 public class HomeController : Controller { public ActionResult Index()未収録
定石1: Windows認証—最小設定でイントラSSO
#e927f6952e5d
// ✅定石3: OWIN Startup.csでのCookie認証設定 using Owin; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies;未収録
定石3: Cookie認証— OWIN + ASP.NET Identity
#646899dc7794
// ✅定石4: [Authorize] 属性で認可制御 public class OrderController : Controller { [Authorize] //ログイン必須(未ログインはLoginUrlにリダイレクト)未収録
定石4: [Authorize]属性で認可制御
#37d5f30b5333
// ✅定石5: User.Identityからの情報取得 public class HomeController : Controller { [Authorize]未収録
定石5: User.Identity.Nameでユーザー情報取得
#5b90d26c7949
