Redirect to requested page after authentication

妖精的绣舞 提交于 2019-12-18 13:08:11

问题


I'm working on an mvc .net application and I'm using forms authentication. I want to redirect user to the page he requested after he gets authenticated. Any help would be appreciated.


回答1:


If you create an ASP.NET MVC 3 or 4 Internet Application project, it'll have a complete example of how to use return url's when authenticating.

When you add the AuthorizeAttribute to a controller to force authentication, it'll redirect the user to your Login method, and automatically append the returnUrl parameter. From there, you need to keep track of it as you show your login form:

public ActionResult Login(string returnUrl)
{
     ViewBag.ReturnUrl = returnUrl;
     return View();
}

and then add it to your login form's route collection:

@*//ReSharper disable RedundantAnonymousTypePropertyName*@
@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
@*//ReSharper restore RedundantAnonymousTypePropertyName*@

}

Once the user submits the login, assuming they authenticate properly, you'll just redirect to returnUrl:

[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
     return RedirectToLocal(returnUrl);
}

The hardest part is keeping track of the ReturnUrl through the GET/POST sequence.

If you want to see how the AuthorizeAttribute works, this StackOverflow post shows setting returnUrl with the original request.

You also need to make sure you validate returnUrl really is a local url, or you become vulnerable to open redirection attacks. RedirectToLocal() is a helper method from the MVC 4 Internet Application template that does this validation:

private ActionResult RedirectToLocal(string returnUrl)
{
     if (Url.IsLocalUrl(returnUrl))
     {
          return Redirect(returnUrl);
     }
     else
     {
          return RedirectToAction("Index", "Home");
     }
}


来源:https://stackoverflow.com/questions/13146032/redirect-to-requested-page-after-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!