私には2つの属性があります:
public class AnonymousAllowedAttribute : AuthorizeAttribute { }
public class ActionAuthorizeAttribute : AuthorizeAttribute {
public override void OnAuthorization(AuthorizationContext filterContext) {
bool skipAuthorization =
filterContext.ActionDescriptor.IsDefined(typeof(AnonymousAllowedAttribute), true)
||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AnonymousAllowedAttribute), true);
if(!skipAuthorization)
base.OnAuthorization(filterContext);
}
bool CustomeCheck() {
bool result = //My Checks
return result;
}
}
ActionAuthorizeAttribute私はグローバル属性として定義します。
だから私はこの3つのアイテムが必要です:
1-ログインしなかった場合(!User.Identity.IsAuthenticated):ログインページに移動しますAccounts/LogIn。LogInでマークされたアクションについて言及する必要がありAnonymousAllowedAttributeます。
2-ログイン(User.Identity.IsAuthenticated)およびアクションまたはコントローラーが持っているAnonymousAllowedAttribute場合、承認はtrueです(承認は必要ありません)。
3-ログイン(User.Identity.IsAuthenticated)とアクションがメソッドをAnonymousAllowedAttribute返さない場合CustomeCheck()
ご覧のとおり、オーバーライドOnAuthorization()メソッドで2番目のものを試します。
そして3番目は次のとおりです。
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext){
if(!httpContext.User.Identity.IsAuthenticated)
return false;
return CustomeCheck();
}
しかし、私がログインしなかったときは常に戻ります:
IIS 7.5エラーの詳細:
HTTPエラー401.0-許可されていません
このURLで:http://myProject/Accounts/LogIn?ReturnUrl=%2f
問題はどこだ?ActionAuthorizeAttributeこの3つの目標を達成するためにどのように実装できますか?
アップデート
私は答えを見つけます:問題は:ではなくAnonymousAllowedAttributeから継承する必要があることです。AttributeAuthorizeAttribute