您可以使用全局操作过滤器。假设您有一个自定义主体:
public class MyPrincipal : GenericPrincipal
{
public MyPrincipal(IIdentity identity, string[] roles): base(identity, roles)
{
}
... some custom properties and stuff
}
然后您可以编写一个全局授权操作过滤器(但它不是从基础派生AuthorizeAttribute
以避免全局身份验证,它只是实现IAuthorizationFilter
接口以确保它在任何其他过滤器之前运行):
public class GlobalIdentityInjector : ActionFilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
var identity = filterContext.HttpContext.User.Identity;
// do some stuff here and assign a custom principal:
var principal = new MyPrincipal(identity, null);
// here you can assign some custom property that every user
// (even the non-authenticated have)
// set the custom principal
filterContext.HttpContext.User = principal;
}
}
全局过滤器将被注册,~/App_Start/FilterConfig.cs
以确保它适用于所有操作:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new GlobalIdentityInjector());
}
}
现在您可以拥有一个自定义授权属性,该属性仅适用于某些需要身份验证的控制器操作:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
return false;
}
// we know that at this stage we have our custom
// principal injected by the global action filter
var myPrincipal = (MyPrincipal)httpContext.User;
// do some additional work here to enrich this custom principal
// by setting some other properties that apply only to
// authenticated users
return true;
}
}
然后你可以有两种类型的动作:
public ActionResult Foo()
{
var user = (MyPrincipal)User;
// work with the custom properties that apply only
// to anonymous users
...
}
[MyAuthorize]
public ActionResult Bar()
{
var user = (MyPrincipal)User;
// here you can work with all the properties
// because we know that the custom authorization
// attribute set them and the global filter set the other properties
...
}