2

MVC4 Web サイトで簡単なフォーム認証をセットアップしようとしています。

App_start/FilterConfig.cs:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
   filters.Add(new HandleErrorAttribute());
   filters.Add(new AuthorizeAttribute());
}

Web.config で:

<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" name=".ASPFORMSAUTH" />
</authentication>
  <authorization>
      <deny users="?" />
</authorization>

コントローラー/AccountController:

[AllowAnonymous]
public ActionResult Login()
{
    return View("~/Views/MyAccountViews/Login.cshtml");
}

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
    ActionResult retVal = View("~/Views/MyAccountViews/Login.cshtml", model); 

    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            retVal = RedirectToAction("Index", "Home");
        } 
    }

    return retVal;
}

これを Visual Studio でデバッグすると、ベース URL (localhost:1111/ など) に到達し、ログイン ページ (localhost:1111/Account/Login?ReturnUrl=%2f) に正しくリダイレ​​クトされます。

ただし、URL を localhost:1111/ に戻して Enter キーを押すだけで、サイトにアクセスできます。このシナリオでは、httpcontext.current.user.identity.name がまだ Windows NT ログイン名です。FormsAuthentication.Logout を呼び出して Cookie をクリアするようにしました。ログインして「PersistCookie」を true に設定し、FormsAuthentication.Logout を呼び出さずにデバッグ セッションを再起動すると、最初はログイン ページにリダイレクトされますが、URL を変更することで回避できます。したがって、Cookie の有無にかかわらず同じ結果になります。これを厳密にフォーム認証で機能させるにはどうすればよいですか? 私は何を間違っていますか?

4

1 に答える 1