これが私が設定した方法です。これが役立つことを願っています:
App_Start/NinjectWebCommon.cs で、ポリシー ハンドラーをバインドします。
kernel.Bind<IPolicyViolationHandler>().To<DenyAnonymousAccessPolicyViolationHandler>();
kernel.Bind<IPolicyViolationHandler>().To<RequireRolePolicyViolationHandler>();
また、Fluent Security を次のように構成します (Ninject Service Locator を使用):
var locator = new NinjectServiceLocator(kernel);
ServiceLocator.SetLocatorProvider(() => locator);
SecurityConfigurator.Configure(
configuration =>
{
configuration.GetAuthenticationStatusFrom(() => HttpContext.Current.User.Identity.IsAuthenticated);
configuration.GetRolesFrom(SecurityHelpers.UserRoles);
//HomeController and other configurations
configuration.For<HomeController>().Ignore();
configuration.ResolveServicesUsing(ServiceLocator.Current.GetAllInstances);
}
);
GlobalFilters.Filters.Add(new HandleSecurityAttribute(), 0);
次に、ポリシーごとに、IPolicyViolationHandler の実装があります。
public class RequireRolePolicyViolationHandler : IPolicyViolationHandler
{
public ActionResult Handle(PolicyViolationException exception)
{
//Make sure you're redirecting to the desired page here. You should put a stop here to debug it and see if it's being hit.
return new HttpUnauthorizedResult(exception.Message);
}
}
カスタム メンバーシップ/ロール プロバイダーと Fluent Security を使用した実用的なソリューションがあります。コア構成と思われるものを投稿しました。お役に立てれば。
編集:役割を取得する方法を追加しました。
public static class SecurityHelpers
{
public static IEnumerable<object> UserRoles()
{
var currentUser = HttpContext.Current.User.Identity.Name;
var roles = Roles.Providers["MemberAccountRoleProvider"]; //Custom Role Provider Name
return currentUser != null ? roles.GetRolesForUser(currentUser).Cast<object>().ToArray() : null;
}
}
編集 2 : 私はあなたのコードを見て、正常に動作しています。これをコードに追加して、必要な場所にリダイレクトできるようにします。現在、Http の結果を返しているだけです。
public class RequireRolePolicyViolationHandler : IPolicyViolationHandler
{
public ActionResult Handle(PolicyViolationException exception)
{
//return new HttpUnauthorizedResult(exception.Message);
return
new RedirectToRouteResult(
new RouteValueDictionary(new { action = "Test", controller = "Account"})); //Created a view for testing
}
}
設定ページを取得しようとすると、RequireRolePolicyViolationHandler が表示されます。
