asp mvc 3 ActionFilter for basic authentication

后端 未结 4 1862
面向向阳花
面向向阳花 2020-12-30 14:29

I have an ASP MVC3 restful service that uses basic authentication. After searching stack overflow, I created the following code.

public class BasicAuthentic         


        
4条回答
  •  被撕碎了的回忆
    2020-12-30 15:00

    1) No, ActionFilter attributes are not a good approach to authenticate a user. (As we need to authenticate once and set authenticate cookie, so HttpContext.User will remain authenticated till cookie expires)

    2) Yes, setting filtercontext.Result is a ideal way to prevent access. ( But Instead of assigning HttpNotFoundResult, use RedirectResult to redirect to login page)

    3) I really don't understand why to have such implementation for Authorization. The best approach would be to have an action that will receive form posted data (username and password). and use Authorize attribute to prevent unauthorize access.

    following is the code from default MVC3 sample application in VS2010.

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
    
            // If we got this far, something failed, redisplay form
            return View(model);
        }
    

提交回复
热议问题