加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 09:41:39 所属栏目:asp.Net 来源:网络整理
导读:在从WebForms到MVC的迁移中,一些.aspx页面仍然存在.这些的身份验证当前是基于文件的,并通过Web.config进行.通过向GlobalFilters.Filters添加AuthorizeAttribute并根据需要向控制器/操作添加MVC身份验证. Web.config身份验证目前看起来像这样: authenticatio
在从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()));
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读