動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About
C#

定石2: Forms認証—フォームログイン+ Cookie

出典: 業務イントラの認証 — Windows認証 / Forms認証 / Cookie の使い分けで業務SE が踏む選択定石2: Forms認証—フォームログイン+ Cookie

定石2: Forms認証—フォームログイン+ Cookie (csharp)#9451e4bcfa68
// ✅定石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 は実行結果未収録
▸ 実行結果は未収録です
  • id: #9451e4bcfa68
  • lines: 33
  • extracted: 2026-06-10

Source収録記事

この snippet は記事の「定石2: Forms認証—フォームログイン+ Cookie」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。

同じ記事から

4
図鑑トップ