0

我在 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

非常感谢任何帮助。

谢谢

4

1 回答 1

1

有类似的东西,但与 Surface 控制器而不是 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.configcustomErrorshttpErrors部分而不是代码来处理)。

可能想查看您的 web.config 设置?

于 2018-08-08T14:55:07.283 回答