为什么需要AuthorizationAttribute
在没有Authorization系统属性之前,我们可能这样判断:
Request.IsAuthenticated && User.Identity.IsAuthenticated来判断请求是否有权限。
有了Authorization系统属性之后,我们可能这样:
[Authorize]
public ActionResult SomeAction()
在Web.config文件中:
<authentication mode="Forms">
<forms loginUrl="~/Home/UnAuthorized" timeout="2880" />
</authentication>
很显然,有了AuthorizeAttribute这种cross-cutting设计,简化了代码,降低了耦合。
通过继承AuthorizationAttribute来扩展
主要是重写AuthorizeCore方法。
class="alt">public class SomeAuthorizationAttribute : AuthorizeAttribute
{
private List<string> blockIps;
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
LoadBockIpAddresses();
return (!blockIps.Contains(httpContext.Request.UserHostAddress));
}
public void LoadBlockIpAddresses()
{
blokedIps = new List<string>();
blockedIps.Add("127.0.0.1");
}
}
使用默认的AuthorizeAttribute
[Authorize(Users="", Roles="")]
public ActionResult SomeAction
同时需要在Web.config中配置:
<authentication mode="Forms">
<forms loginUrl="~/Home/UnAuthorized" timeout="2880">
<credentials>
<user name="name" password="name"/>
</credentials>
</forms>
</authentication>
<roleManager enabled="true" cacheRolesInCookie="true" />
参考资料:
MVC Filters Part 1 - Authorization Filter