[英]Api with 401 status returning login page
我已经在UmbracoApiController下创建了一个POST API。
[HttpPost]
[ActionName("SaveData")]
public HttpResponseMessage SaveData([FromBody]JObject data)
{
if (!authorized)
{
return Request.CreateResponse(HttpStatusCode.Unauthorized,
"Unauthorized access. Please check your credentials");
}
}
它不返回401,而是转到状态为302的登录页面。
我也创建了一个自定义属性-
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class BasicAuthorization : AuthorizationFilterAttribute
{
private const string _authorizedToken = "Authorization";
public override void OnAuthorization(HttpActionContext filterContext)
{
var authorizedToken = string.Empty;
try
{
var headerToken = filterContext.Request.Headers.FirstOrDefault(x => x.Key == _authorizedToken);
if (headerToken.Key != null)
{
authorizedToken = Convert.ToString(headerToken.Value.SingleOrDefault());
if (!IsAuthorize(authorizedToken))
{
var httpContext = HttpContext.Current;
var httpResponse = httpContext.Response;
filterContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent("Unauthorized access. Please check your credentials")
};
httpResponse.StatusCode = (int) HttpStatusCode.Unauthorized;
httpResponse.SuppressFormsAuthenticationRedirect = true;
return;
}
}
else
{
filterContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
return;
}
}
catch (Exception)
{
filterContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
return;
}
base.OnAuthorization(filterContext);
}
private static bool IsAuthorize(string authorizedToken)
{
return authorizedToken == ConfigurationManager.AppSettings["VideoIngestionKey"];
}
}
但这也不起作用。 我正在使用Umbraco 7.6.13
任何帮助,不胜感激。
谢谢
有类似的东西,但与Surface Controller而非Web API控制器一起使用。
覆盖HandleUnauthorizedRequest
以实现自定义响应/覆盖Umbraco和.NET默认值。
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// example redirects to a 'Forbidden' doctype/view with Reponse.StatusCode set in view;
filterContext.Result =
new RedirectToUmbracoPageResult(
UmbracoContext.Current.ContentCache.GetSingleByXPath("//forbidden"));
}
奇怪的是,Forms身份验证似乎开始生效,并将您重定向到API请求的登录页面。 默认情况下, AuthorizationFilterAttribute
应该返回Http 401(因此可以通过web.config customErrors
或httpErrors
部分代替代码来处理)。
可能想查看您的web.config设置?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.