且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

基于用户角色的ASP.NET MVC 5身份2登录重定向

更新时间:2023-02-24 20:57:06

你为什么不自定义重定向前检查是否有RETURNURL?

why dont you check if there is a returnUrl before your custom redirects?

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
         if (ModelState.IsValid)
         {
              var user = await UserManager.FindAsync(model.UserName, model.Password);
              if (user != null)
              {
                    await SignInAsync(user, model.RememberMe);
                    if (String.IsNullOrEmpty(returnUrl))
                    {
                         if (UserManager.IsInRole(user.Id, "Employer"))
                         {
                             return RedirectToAction("Index", "Employer");
                         }
                         //role Admin go to Admin page
                         if (UserManager.IsInRole(user.Id, "Admin"))
                         {
                             return RedirectToAction("Index", "Admin");
                         }
                     }
                     else
                     {
                         return RedirectToLocal(returnUrl);
                     }
              }
              else
              {
                     ModelState.AddModelError("", "Invalid username or password.");
              }
       }

       // If we got this far, something failed, redisplay form
       return View(model);
   }

像这个,如果你浏览到foo.com/admin~~V将抛出401和重定向您登录。然后,如果你登录为雇主会抛出401和重定向你回来重新登录。

Like this if you navigate to foo.com/admin it will throw 401 and redirect you to login. Then if you log in as employer it will throw 401 and redirect you back to login again.

从评论:?可我就是重定向(RETURNURL),并删除RedirectToLocal操作方法

From comments: "Can I just do Redirect(returnUrl) and delete the RedirectToLocal action method?"

RedirectToLocal(RETURNURL)方法检查 Url.IsLocalUrl(RETURNURL)。因此,它是需要prevent打开重定向攻击。

RedirectToLocal(returnUrl) method checks if Url.IsLocalUrl(returnUrl). So it is needed to prevent Open Redirect Attacks.