ASP.NET MVC身份验证通过重定向到登录页面然后返回

Ale*_*mov 1 authentication asp.net-mvc

我有一个ASP.NET MVC网站.我有许多需要执行身份验证的操作.因此,我需要将用户重定向到登录页面,并在登录后(如果成功)重定向回来.所以我现在要做的是建立一个新的类,smth.有点见下图:

class AuthChecker
 {
    public AuthChecker(string authActionName, string authControllerName)
    {
      //...
    }

    public ActionResult InvokeIfAuthenticated(Func<ActionResult> body, string errorNoAuth, string returnUrl)
    {
         if (Request.IsAuthenticated)
         {
           return body();
         }
         else
         {
           //set returnUrl and return RedirectToAction(authAction);
         }
    }
 }
Run Code Online (Sandbox Code Playgroud)

那可以吗,或者有一些开箱即用的解决方案来管理这种情况?或者可能有更好的解决方案?

Jac*_*tti 5

你正在寻找Authorize属性.

例如[来自以下链接]:

 [Authorize]
 public ActionResult AuthenticatedUsers()
 {
     return View();
 }

 [Authorize(Roles = "Admin, Super User")]
 public ActionResult AdministratorsOnly()
 {
     return View();
 }

 [Authorize(Users = "Betty, Johnny")]
 public ActionResult SpecificUserOnly()
 {
     return View();
 }
Run Code Online (Sandbox Code Playgroud)

限制对操作方法的访问