在从WebForms迁移到MVC时,仍会保留一些.aspx页面。这些的身份验证当前是基于文件的,并通过Web.config进行。通过向AuthorizeAttribute
添加GlobalFilters.Filters
并根据需要向控制器/操作添加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过滤器。我一直无法找到这方面的一个例子。这甚至是可能的,这样做有什么不良影响吗?
我知道默认情况下MVC挂钩不会处理.aspx文件。
我正在寻找一种方法来获取所有.aspx文件,无论他们的代码隐藏基类是什么。
答案 0 :(得分:1)
在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()));
}