Two-step authentication in MVC?

We have an MVC application that has an authentication view / controller for personalized forms. The controller checks everything and then makes a call to FormsAuthentication.RedirectFromLoginPage.

At this point in Global.asax we will receive a call to Application_OnAuthenticateRequest, from where we will get information about Context.User and make another call to collect information related to this account, which we then store in their Context.User and System.Threading.Thread .CurrentPrincipal. We also cache this information a bit, since in our system we get what we need dear, which leads to the invalidity of the cache and the repeated extraction of this information.

At this point, it seems a little strange that we divided them into separate challenges. I am almost wondering if the input controller should not collect the details as part of the authentication and storage of them. Then Application_OnAuthenticateRequest can only worry about the cache being invalid and user data retransmitted.

Or maybe there is another way to handle this that I don’t even know about.

+2
source share
1 answer

You can do what you want in MVC using RedirectToRouteResult and updating the custom ActionFilter cache. This is called a PRG (Post-Redirect-Get) pattern. You actually already do this, but it gets a little confused because what you do is a cross between the classic ASP.NET way and MVC things. There is nothing wrong with your initial approach (assuming that it works correctly), but do the same and have more control and understanding of how it works in a scheme of things that you could do something like this:

 public class AuthenticationController :Controller { [HttpPost] public RedirectToRouteResult Login(string username, string password) { //authenticate user //store authentication info in TempData like bool authenticated = true|false; // do your testing if(authenticated) { TempData["MustUpdateCache"] = true | false; return RedirectToAction("LoginSuccess", new{userId = membershipUser.UserId}); } else { TempData["MustUpdateCache"] = true | false; return RedirectToAction("Login"); } } [HttpGet, UpdateCache] public ActionResult LoginSuccess(Guid userId, string url) { HttpContext.User = LoadUser(userId); return View(); } [HttpGet, UpdateCache] public ViewResult Login() { return View(); } } public class UpdateCacheAttribute:ActionFilterAttribute { public override void OnResultExecuting(ResultExecutingContext filterContext) { var tempData = filterContext.Controller.TempData; if (tempData.ContainsKey("MustUpdateCache") && (bool)tempData["MustUpdateCache"]) { UpdateCache(filterContext); } } void UpdateCache(ControllerContext controllerContext) { //update your cache here } } 
+2
source

Source: https://habr.com/ru/post/888950/


All Articles