nra*_*rez 5 c# api ajax authorize-attribute asp.net-mvc-4
我的自定义AuthorizeAttribute遇到了一些问题
public class ExplicitAuthorizeAttribute : AuthorizeAttribute
{
private readonly MembershipUserRole[] _acceptedRoles;
public ExplicitAuthorizeAttribute()
{
}
public ExplicitAuthorizeAttribute(params MembershipUserRole[] acceptedRoles)
{
_acceptedRoles = acceptedRoles;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//Validation ...
}
}
Run Code Online (Sandbox Code Playgroud)
我这样使用它:
[ExplicitAuthorize[(MembershipUserRole.Admin, MembershipUserRole.SuperAdmin)]
Run Code Online (Sandbox Code Playgroud)
它非常适合HttpGet和HttpPost验证我的控制器和方法.
但是当我在ApiController中使用它并进行ajax调用时,AuthorizeCore没有运行,我遇到了安全漏洞.:/
我的枚举看起来像这样
[Flags]
public enum MembershipUserRole
{
Admin= 1,
SuperAdmin = 2
}
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么我的AuthorizeCore在这种情况下没有验证?
顺便说一下如果我用
[Authorized(Roles ="Admin, SuperAdmin")]
Run Code Online (Sandbox Code Playgroud)
这是完美的验证,但我想要Stronly Typed Roles,这就是我使用枚举的原因.
您派生自错误的类:System.Web.Mvc.AuthorizeAttribute而对于Web API控制器,您应该派生自System.Web.Http.AuthorizeAttribute.
不要忘记ASP.NET MVC和ASP.NET Web API是两个完全不同的框架,即使它们共享一些共同的原则和名称,相应的类也位于两个完全不同的名称空间中.
所以你所做的就是用一个它不知道的AuthorizeAttribute来装饰一个ASP.NET Web API动作.
如果要在ASP.NET Web API中进行授权,请确保从正确的属性派生:
public class ExplicitAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
private readonly MembershipUserRole[] _acceptedRoles;
public ExplicitAuthorizeAttribute()
{
}
public ExplicitAuthorizeAttribute(params MembershipUserRole[] acceptedRoles)
{
_acceptedRoles = acceptedRoles;
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
//Validation ...
}
}
Run Code Online (Sandbox Code Playgroud)