我有一个 CustomApiAuthorizeAttribute:
public class CustomApiAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext == null)
throw new ArgumentNullException("actionContext");
bool skipAuthorization = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any() ||
actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (skipAuthorization) return;
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
var decCookie = FormsAuthentication.Decrypt(cookie.Value);
if (decCookie != null)
{
if (!string.IsNullOrEmpty(decCookie.UserData))
{
HttpContext.Current.User = new CustomPrinciple(new CustomIdentity(decCookie));
return;
}
}
}
HttpContext.Current.Items["RequestWasNotAuthorized"] = true;
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName) { Expires = DateTime.Now.AddDays(-1d) });
HandleUnauthorizedRequest(actionContext);
}
}
我有一个 Controller :
[CustomApiAuthorize]
public class RacingController : CustomApiController
{
[HttpGet]
[AllowAnonymous]
public Venues Venues()
{
var asr = Services.GetVenues(Token);
if(!string.IsNullOrEmpty(Token))
SetAuthTicket(asr.Token);
return asr.Payload;
}
}
尝试调用此操作时,我不断收到 401 未经授权的错误。调试告诉我 authorizeattribute 没有检测到 [AllowAnonymous] 的存在,但我不明白为什么。
有人能看出我做错了什么吗?或者知道是否有其他事情可能会发生冲突?
最佳答案
如果您查看 System.Web.Http.AuthorizeAttribute 的源代码,会进行以下检查以查看是否应跳过授权:
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext == null)
{
throw Error.ArgumentNull("actionContext");
}
if (SkipAuthorization(actionContext))
{
return;
}
if (!IsAuthorized(actionContext))
{
HandleUnauthorizedRequest(actionContext);
}
}
private static bool SkipAuthorization(HttpActionContext actionContext)
{
Contract.Assert(actionContext != null);
return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any()
|| actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
}
所以我所做的是在我的自定义授权属性中实现类似的检查。
关于c# - 自定义 Api 授权忽略 AllowAnonymous,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19671411/