自定义 API 授权忽略允许匿名
本文关键字:许匿名 API 授权 自定义 | 更新日期: 2023-09-27 18:37:27
我有一个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);
}
}
我有一个控制器:
[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 未授权错误。 调试告诉我授权属性没有检测到 [允许匿名] 的存在,但我不明白为什么。
任何人都可以看到我做错了什么吗?或者知道是否有其他冲突?
如果您查看 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();
}
所以我所做的是在我的自定义授权属性中实现类似的检查。