グローバルアクションフィルターを使用できます。カスタムプリンシパルがあるとしましょう。
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;
}
}
次に、2種類のアクションを実行できます。
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
...
}