[英]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.