ASP.net MVC表单身份验证和授权问题

时间:2017-06-21 15:25:19

标签: c# asp.net-mvc asp.net-mvc-4

我正在使用表单身份验证,并希望在身份验证之前限制用户访问其他URL。

对于来自身份验证,我正在使用Cookie。登录/注销工作正常。 目前的流程是:

Login (GET) --> Login(POST)--> Home Page --> Logout

当我对[Authorize]的任何特定Action方法应用HomeController属性时,流程停止工作。

这是我的帐户管理员:

[AllowAnonymous]
public ActionResult Login()
{
    ......
}

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(Model model,string Id)
{
   ..........
   return RedirectToAction("Index", "Home");
}

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Logoff()
{
  .....
}

如果我把 [授权] 上面的家庭控制器的操作方法“索引”:

[Authorize]
[Route("/Home/Index")]
public ActionResult Index()
{
.......
}

Login方法重定向到自身:

Login (GET) --> Login(POST) --> Login(GET)

以下是Forms身份验证的web.config设置:

<authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

修改 我的登录(POST)方法如下所示: -

        if (IsAuthorized(username, password))
        {
            string groups = getUSergroups();//method to get groups where the user belongs to
            bool isCookiePersistent = false;
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
                                                             model.Username, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, groups);

            //Encrypt the ticket.
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            //Create a cookie, and then add the encrypted ticket to the cookie as data.
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

            if (true == isCookiePersistent)
                authCookie.Expires = authTicket.Expiration;

            //Add the cookie to the outgoing cookies collection.
            Response.Cookies.Add(authCookie);



            return RedirectToAction("Index", "Home");
        }

任何人都可以建议任何输入来实现这一目标吗?

0 个答案:

没有答案