MVC ASP.NET - Manually authorize someone and persist the authorization via Forms Authentication

前端 未结 3 1719
無奈伤痛
無奈伤痛 2021-02-04 11:38

I want the benefits of form authentication in ASP.NET. I want it to persist the authorization for me and such, but there\'s one thing different about my situation; I want to au

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-04 12:18

    In forms authentication isn't the proof of who you are in th forms authentication cookie.? With that in mind couldn't you create the ticket in a custom login form without having to create a custom provider? I would definitely think you could. Do a quick test and create a forms authentication ticket and see if the out of the box membership provider considers the user authenticated.

    I was curious-- so here is some code..

    Model

    public class SignInViewModel
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
    

    Controller

    public class SignInController : Controller
    {
    
        public ActionResult Index()
        {
            var model = new SignInViewModel {};
            return View(model);
        }
    
        [HttpPost]
        public ActionResult Index(SignInViewModel model)
        {
            if (model.Username == "Fred" && model.Password == "Mertz")
            {
                FormsAuthentication.SetAuthCookie(model.Username, false);
                return RedirectToAction("Secure");
            }
            return View(model);
        }
    
        [Authorize]
        public ActionResult Secure(SignInViewModel model)
        {
            return View();
        }
    
        [Authorize]
        public ActionResult Logout(SignInViewModel model)
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index");
        }
    

    Index.cshtml

    @using (Html.BeginForm()) {
        
    SignInViewModel
    @Html.LabelFor(model => model.Username)
    @Html.EditorFor(model => model.Username) @Html.ValidationMessageFor(model => model.Username)
    @Html.LabelFor(model => model.Password)
    @Html.EditorFor(model => model.Password) @Html.ValidationMessageFor(model => model.Password)

    }

    Secure.cshtml

    Secure

    @Html.ActionLink("Logout", "Logout")

提交回复
热议问题