I am working on a project that consists of asp.net mvc (in particular, the authorization page) and parts on angularjs (fully SPA).

At the moment, when you try to follow any link, it redirects to the authorization page, but after authorization (when the log in button is pressed) the user is taken to the default page, which is defined in the action method.

It is required that the redirect be to the link that the user tried to open from the very beginning. If not tried, then send to default.

How to configure this redirection process if the user is not authorized?

The controller and the action method to confirm the authorization is already there: on the view, in addition to input for the login and password, there is also a hidden input intended for the url that the user wanted to go to.

 public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(LoginModel model, string returnUrl) { if (!ModelState.IsValid) return View(model); var password = PasswordHash.Encrypt(model.Password); var user = _userManagerService.GetUser(model.Username, password); if (user != null) { FormsAuthHelper.SetAuthenticationCookie(Response, user); if (returnUrl.Length > 1) { return Redirect(returnUrl); } return RedirectToAction("Index", "Invoice"); } ModelState.AddModelError("", "The user name or password provided is incorrect."); // If we got this far, something failed, redisplay form return View(model); } 
  • Why are you doing this? If you have a SPA, do authorization there too. - Pavel Mayorov
  • I am working on a very large project, it is not possible to just take it and completely make a SPA :), so this question is only about MVC asp - simply good

1 answer 1

The value from the "referer" header (when requesting a form) is put in a hidden form field, for example. If the value is not found - redirect to the default page.

 public class AutorizedOnly : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); if (/*is NOT autorized*/) { Uri returnTo = filterContext.HttpContext.Request.UrlReferrer; filterContext.Result = RedirectToAction("Login", "Accounting", new { returnUrl = returnTo }); } } } public class Accounting : Controller { ... [HttpGet] public IActionResul Login(Uri returnTo) { ViewBag.returnTo = returnTo.ToString(); return View(); } [HttpPost] public IActionResul Login(string returnTo, SignInModel model) { if (ModelState.IsValid) { if (/*login success*/) { /* Set cookie with session id */ return Redirect(returnTo); } } ... } ... } 
  • Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin