【问题标题】:Authorization with Session variables in asp net mvc 5在 asp net mvc 5 中使用会话变量进行授权
【发布时间】:2015-05-21 11:10:45
【问题描述】:

所以我的项目需求发生了变化,现在我认为我需要构建自己的操作过滤器。

所以,这是我当前的登录控制器:

 public class LoginController : Controller
{
    // GET: Login
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]

    public ActionResult Login(LoginViewModel model)
    {  
        string userName = AuthenticateUser(model.UserName, model.Password);
        if (!(String.IsNullOrEmpty(userName)))
        {
            Session["UserName"] = userName;
            return View("~/Views/Home/Default.cshtml");
        }

        else
        {
            ModelState.AddModelError("", "Invalid Login");
            return View("~/Views/Home/Login.cshtml");
        }
    }

    public string AuthenticateUser(string username, string password)
    {
        if(password.Equals("123")
            return "Super"
        else
            return null;
    }

    public ActionResult LogOff()
    {
        Session["UserName"] = null;
        //AuthenticationManager.SignOut();
        return View("~/Views/Home/Login.cshtml");
    }
}

这是我的动作过滤器尝试:

public class AuthorizationFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (HttpContext.Current.Session["UserName"] != null)
        {
            filterContext.Result = new RedirectToRouteResult(
                   new RouteValueDictionary{{ "controller", "MainPage" },
                                      { "action", "Default" }

                                     });
        }
        base.OnActionExecuting(filterContext);
    }
}

我已经将它添加到 FilterConfig,但是当我登录时它不会加载 Default.cshtml,它只是不断循环操作过滤器。它的操作结果如下所示:

//这个位于MainPage控制器中

 [AuthorizationFilter]
    public ActionResult Default()
    {
        return View("~/Views/Home/Default.cshtml");
    }

那么,我需要添加什么才能授予授权,以便只有经过身份验证的用户才能查看应用程序的页面?我应该使用会话变量还是有另一种/更好的方法来使用?我几乎坚持使用 AuthenticateUser(),因为现在发生的只是一个简单的比较,就像我们现在的比较。

感谢您的宝贵时间。

【问题讨论】:

  • 澄清一下,您已将 AuthorizationFilter 添加到 FilterConfig 中?
  • @WillSmith 是的,我将它添加到 FilterConfig
  • 为什么不能在控制器上使用内置的[Authorize] 属性?
  • @Coulton 当我的 AuthenticateUser 看起来像这样时,我该如何使用?严肃的问题,根据我在这种情况下所读到的内容,我必须建立自己的。
  • 不创建标准FilterAttribute,而是将其创建为AuthorizationAttribute msdn.microsoft.com/en-us/library/ee707357%28v=vs.91%29.aspx

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

用你的逻辑创建一个AuthorizeAttribute

public class AuthorizationFilter : AuthorizeAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
            || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
        {
            // Don't check for authorization as AllowAnonymous filter is applied to the action or controller
            return;
        }

        // Check for authorization
        if (HttpContext.Current.Session["UserName"] == null)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

只要您在Startup.Auth.cs 文件中配置了登录 URL,它就会为您处理到登录页面的重定向。如果您创建一个新的 MVC 项目,它会为您配置:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(
            new CookieAuthenticationOptions {

                    // YOUR LOGIN PATH
                    LoginPath = new PathString("/Account/Login")
            }
        );
    }
}

如果您想阻止检查某些控制器或操作的授权,您可以使用 [AuthorizationFilter][AllowAnonymous] 属性来装饰您的控制器。

您可能希望在不同的场景中对此进行检查,以确保它提供足够严格的安全性。 ASP.NET MVC 提供了可以开箱即用的机制来保护您的应用程序,如果可能的话,我建议在任何情况下使用这些机制。我记得有人对我说,如果你想为自己做身份验证/安全,你可能做错了。

【讨论】:

  • 我做了一些研究,似乎重写 onAuthorization 是个坏主意,因为它做了一些特殊的事情来避免缓存提供页面。
  • 感谢您告诉我。我很想知道这方面的更多细节,你有链接吗?
  • 我阅读了源代码,其中有一个重要的通知就是关于这一点的。 github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/…
  • 由于每个请求都必须首先检查身份验证,所以我简单地覆盖了 AuthorizationCore 函数并在其中执行所有逻辑。
  • 听起来是一个合理的解决方案。感谢您让我注意到这一点,我还没有触及任何 ASP.NET MVC 的缓存机制,所以当我这样做时我会记住这一点!
【解决方案2】:

由于您的属性已添加到 FilterConfig,它将应用于所有操作。因此,当您导航到 MainPage/Default 操作时,它将应用过滤器并将您重定向到 MainPage/Default 操作(等等......)。

您将需要:

  • 将其从 FilterConfig 中移除并将其应用于适当的操作/控制器
  • 或在过滤器中添加额外检查,使其不会在某些路由上重定向

【讨论】:

  • 感谢您的回答,我尝试了第一个,将其从 FilterConfig 中删除,但它停止工作,正在考虑添加额外的检查以防止它一遍又一遍地重定向到同一页面。
  • 你也可以考虑使用内置的AuthenticationAttribute & FormsAuthentication
猜你喜欢
  • 2015-08-02
  • 2017-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
相关资源
最近更新 更多