【问题标题】:Custom Authentication In MVCMVC 中的自定义身份验证
【发布时间】:2016-07-26 09:49:28
【问题描述】:

我设置了自定义身份验证,以便将用户存储为会话变量。一旦他们完成了帐户/登录过程,我将从 3rd 方 API 返回的详细信息作为用户存储在会话中,如下所示:

Session["User"] = new UserViewModel(result);

我想在每个控制器操作之前检查用户是否存在,因此我制作了一个 BaseController 并在其中进行了以下检查:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
  if (Session["User"] != null)
    base.OnActionExecuting(filterContext);
  else
    filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { action = "LogIn", controller = "Account" }));

然后,每个控制器都从 BaseController 继承,以便在没有用户时重定向到登录页面。我没有从 AccountController 的 BaseController 继承,因此它不会进入检查和重定向的无限循环,但我也希望特定页面不检查登录。有没有办法做到这一点,即以您可能拥有 [AllowAnonymous] 的相同方式编写异常规则?

【问题讨论】:

  • 为什么不创建一个自定义的 Authorize 属性,并将其仅应用于您希望执行此检查的控制器?
  • 覆盖授权属性而不是 ActionFilters

标签: asp.net-mvc


【解决方案1】:

您可以对这些方法使用过滤器:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class ActionCheckAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower().Trim();
        string actionName = filterContext.ActionDescriptor.ActionName.ToLower().Trim();

        // this is just a sample.. you can implement any logic you want
        if (!actionName.StartsWith("your method name") && !controllerName.StartsWith("your controller name"))
        {
            var session1 = HttpContext.Current.User.Identity.Name;
            HttpContext ctx = HttpContext.Current;
            //Redirects user to login screen if session has timed out
            if (session1 == null)
            {
                base.OnActionExecuting(filterContext);

                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                {
                    controller = "Account",
                    action = "LogOff"
                }));
            }
       }

    }
}

然后在控制器上将属性设置为:

[ActionCheck]
public class MyController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

或具体的操作方法如:

[ActionCheck]
public Actionresult SomeMethod()
{
    return View();
}

【讨论】:

    猜你喜欢
    • 2016-02-21
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多