asp.net – WebForms身份验证作为MVC过滤器

在从WebForms到MVC的迁移中,一些.aspx页面仍然存在.这些的身份验证当前是基于文件的,并通过Web.config进行.通过向GlobalFilters.Filters添加AuthorizeAttribute并根据需要向控制器/操作添加MVC身份验证.

Web.config身份验证目前看起来像这样:

<authentication mode="Forms">
  <forms loginUrl="~/SignIn.aspx" protection="All" path="/" timeout="10080" />
</authentication>
<authorization>
  <deny users="?" />
  <allow users="*" />
</authorization>

<location path="SomePage.aspx">
<system.web>
  <authorization>
    <allow roles="Administrator, BasicUser" />
    <deny users="*" />
  </authorization>
</system.web>
</location>

但是,我想将WebForms身份验证从Web.config转移到使用方法调用执行检查的MVC过滤器.我一直无法找到这方面的一个例子.这是否可能,是否有任何不良影响?

我知道.aspx文件默认不由MVC钩子处理.

我正在寻找一种方法来获取所有.aspx文件,无论他们的代码隐藏的基类是什么.

最佳答案 在Global.asax.cs中,

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    // Since MVC does not handle authentication for .aspx pages, do this here.
    AuthController.AuthenticateAspxPage(this.Context);
}

在AuthController中,对于某些类型的UserRole,

public const string ErrorRedirectUrl = "~/Auth/Error";

private static readonly IDictionary<string, UserRole[]> _aspxAccessRoles =
    new Dictionary<string, UserRole[]>()
    {
        { "~/SomePage.aspx", new UserRole[] { UserRole.Administrator,
                                              UserRole.BasicUser } },
          ...
    };

然后,

[NonAction]
public static void AuthenticateAspxPage(HttpContext context)
{
    string ext = context.Request.CurrentExecutionFilePathExtension;
    string aspxPage = context.Request.AppRelativeCurrentExecutionFilePath;
    ClaimsPrincipal principal = context.User as ClaimsPrincipal;

    if ((ext == ".aspx" || ext == ".ashx") && !HasAspxAccess(aspxPage, principal))
    {
        context.Response.Redirect(ErrorRedirectUrl);
    }
}

[NonAction]
public static bool HasAspxAccess(string aspxPage, ClaimsPrincipal principal)
{
    if (principal == null || principal.Claims == null)
    {
        return false;
    }

    string[] userRoles = principal.Claims
        .Where(claim => claim.Type == ClaimTypes.Role)
        .Select(claim => claim.Value)
        .ToArray();

    UserRole[] accessRoles;

    return _aspxAccessRoles.TryGetValue(aspxPage, out accessRoles)
        && accessRoles.Any(role => userRoles.Contains(role.ToString()));
}
点赞