2016-12-13 16 views
3

私は現在、ユーザーロールに基づいて新しいASP MVC 5アプリケーションでセキュリティを実装しようとしています。目的は、ユーザーが特定の役割(またはそれ以上)を持っていない場合に、特定のコントローラーまたはコントローラーの方法にアクセスできないようにすることです。私はこれまでの質問に読んだものに基づいて、私はこのようになりますAuthorizeAttributeを継承する属性(MyAppRoleがところで、列挙型である)作成:AuthorizeAttributeから継承する属性が機能しない

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 
public sealed class AuthorizeRoleOrSuperiorAttribute : AuthorizeAttribute 
{ 
    private MyAppRole _authorizedRole; 

    public AuthorizeRoleOrSuperiorAttribute(MyAppRole authorizedRole) 
    { //Breakpoint here 
     _authorizedRole = authorizedRole; 
    } 

    public override void OnAuthorization(HttpActionContext actionContext) 
    { //Breakpoint here 
     base.OnAuthorization(actionContext); 

     if (!UserInfo.GetUserRoles().Any(r => (int)r >= (int)_authorizedRole)) 
      throw new UnauthorizedAccessException(ErrorsModule.RoleMissing); 
    } 
} 

をそして私は方法でこのようにそれを呼び出すと/またはコントローラ:

[AuthorizeRoleOrSuperior(MyAppRole.Admin)] 
public class MyController : Controller 
{ 
    [AuthorizeRoleOrSuperior(MyAppRole.Admin)] 
    public ViewResult Index() 
    { 
     [...] 
    } 

    [...] 
} 

私は、コンストラクタとOnAuthorizationメソッドにブレークポイントを置いたが、私はアプリを起動し、関係コントローラまたはメソッドを呼び出すときに、私はそれらのいずれかをヒットしたことがないとアクションがあっても、と呼ばれています私もログインしていません。

注:AuthorizeAttributeは使用時に正しく動作しています。

アトリビュートがアクセスとフィルタリングのアクセスを妨げる原因は何でしょうか?

答えて

3

System.Web.Http.AuthorizeAttributeから属性を継承していますか?これはSystem.Web.Mvc.AuthorizeAttributeとは異なる動作をします。

代わりにSystem.Web.Mvc.AuthorizeAttributeから継承してください。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 
public sealed class AuthorizeRoleOrSuperiorAttribute : System.Web.Mvc.AuthorizeAttribute 
{ 
    private MyAppRole _authorizedRole; 

    public AuthorizeRoleOrSuperiorAttribute(MyAppRole authorizedRole) 
    { //Breakpoint here 
     _authorizedRole = authorizedRole; 
    } 

    public override void OnAuthorization(AuthorizationContext filterContext) 
    { //Breakpoint here 
     base.OnAuthorization(filterContext); 

     if (!UserInfo.GetUserRoles().Any(r => (int)r >= (int)_authorizedRole)) 
      throw new UnauthorizedAccessException(ErrorsModule.RoleMissing); 
    } 
} 

少なくとも、ブレークポイントにヒットする必要があります。中

注パラメータ差: OnAuthorization(AuthorizationContext filterContext)public override void OnAuthorization(HttpActionContext actionContext)

また、正しい401のHTTPステータスコードを取得するにはfilterContext.Result = new HttpUnauthorizedResult();を設定することができます。

+0

おかげで、それはまさに私が探していたものでした。これからは、継承したクラスの名前空間に注意してください... – ZipionLive

関連する問題