简体   繁体   English

成功登录后无法重定向到原始页面

[英]Can't redirect to original page after successful login

I've changed the web.config file adding the following lines. 我更改了web.config文件,添加了以下几行。

<system.web>
  <authorization>
    <deny users="?"/>
  </authorization>
  <authentication mode="Forms">
    <forms loginUrl="~/Account/LogIn"></forms>
  </authentication>
</system.web>

Now, whatever page's accessed, I'm being redirected to the login page. 现在,无论访问了什么页面,我都将被重定向到登录页面。 That's great and as I enter the credentials, I'd like the user to be directed back to where they started. 太好了,当我输入凭据时,我希望将用户引导回他们的起点。

public ActionResult LogIn(string token)
{
  using (Model model = new Model())
    if (model.Users.Any(_ => _.Token == token))
      return Redirect(Request.UrlReferrer.ToString());
  return View();
}

The problem I discover is that the UrlReferrer is the login page itself so I'm only redirecting to where I'm already at on the log in page, instead of where I originally started... 我发现的问题是UrlReferrer本身就是登录页面,因此我仅重定向到登录页面上已经存在的位置,而不是我最初开始的位置。

What am I doing wrong? 我究竟做错了什么?

What am I doing wrong? 我究竟做错了什么?

You are using the old ASP.NET security (which is based on physical files and folders) for MVC (which is based on controllers and actions). 您正在使用旧的ASP.NET安全性(基于物理文件和文件夹)进行MVC(基于控制器和操作)。 The proper way to secure controllers and actions is to use AuthorizeAttribute . 确保控制器和动作安全的正确方法是使用AuthorizeAttribute ASP.NET security won't work for MVC controllers because they are not file-system based (but do note it does still come in handy for physical files - you can block direct access to them and then use a controller to provide conditional access). ASP.NET安全性不适用于MVC控制器,因为它们不是基于文件系统的(但请注意,它仍可用于物理文件-您可以阻止对它们的直接访问,然后使用控制器提供条件访问) 。

When you use AuthorizeAttribute , the login URL will automatically be built with a ReturnUrl query string parameter which is used to redirect the user back to the location they started at. 当您使用AuthorizeAttribute ,将使用ReturnUrl查询字符串参数自动构建登录URL,该参数用于将用户重定向回其起始位置。

For example, in the default MVC templates, this is the Login method which uses the returnUrl . 例如,在默认的MVC模板中,这是使用returnUrlLogin方法。 It also uses RedirectToLocal to ensure someone doesn't exploit the query string parameter to hijack the user to another website. 它还使用RedirectToLocal来确保某人不会利用查询字符串参数将用户劫持到另一个网站。

MVC 4 (Simple Membership): MVC 4(简单成员资格):

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        {
            return RedirectToLocal(returnUrl);
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }

MVC 5 (Identity): MVC 5(身份):

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // This doesn't count login failures towards account lockout
        // To enable password failures to trigger account lockout, change to shouldLockout: true
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

Pass Through 通过

You need to pass through the original page through your login process, assuming you want to use the URLReferrer it might look something like this. 您需要在登录过程中浏览原始页面,假设您想使用URLReferrer,它可能看起来像这样。

[HttpGet]
public ActionResult LogIn()
{
  Viewbag.ReturnURL = Request.UrlReferrer.ToString();
  return View();
}

[HttpPost]
public ActionResult LogIn(string token, string returnURL)
{
  using (Model model = new Model())
    if (model.Users.Any(_ => _.Token == token))
      return Redirect(returnURL);
  return View();
}

Warning: Using the UrlReferrer property can be error prone because it relies on information that may be unpredictable depending on the circumstances in which the request occurred. 警告:使用UrlReferrer属性可能容易出错,因为它依赖于根据请求发生的环境可能无法预测的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM