重定向到身份验证后请求的页面 [英] Redirect to requested page after authentication

查看:101
本文介绍了重定向到身份验证后请求的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个MVC .NET应用程序,我使用窗体身份验证。我想用户重定向到他通过认证后,他请求的页面。任何帮助将是AP preciated。

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.

推荐答案

如果您创建一个ASP.NET MVC 3或4的互联网应用程序项目,这将有怎样的回报的URL进行身份验证时使用一个完整的例子。

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.

当您添加AuthorizeAttribute到控制器强制认证,这将用户重定向到您的登录方式,并自动追加RETURNURL参数。从那里,你需要跟踪它为你显示你的登录表单:

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:

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {

}

一旦用户提交的登录,假设他们正确验证,你只重定向到RETURNURL:

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);
}

最难的部分是通过GET / POST序列跟踪的RETURNURL的。

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

如果你想看到的AuthorizeAttribute是如何工作的,<一个href=\"http://stackoverflow.com/questions/379506/forms-authentication-asp-net-mvc-absolute-returnurl\">this计算器后显示设置RETURNURL与原来的要求。

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

您还需要确保您验证RETURNURL真的是一个本地URL,或者你变得脆弱打开重定向攻击。 RedirectToLocal()是从MVC 4互联网应用程序模板,这是否验证一个辅助方法:

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");
     }
}

这篇关于重定向到身份验证后请求的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆