简体   繁体   English

带有401状态的api返回登录页面

[英]Api with 401 status returning login page

I have created a POST API under UmbracoApiController. 我已经在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");
        }
    }

Instead of returning 401, it is going to the login page with 302 status. 它不返回401,而是转到状态为302的登录页面。

I have created a custom attribute as well - 我也创建了一个自定义属性-

 [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"];
    }
}

But this also does not work. 但这也不起作用。 I am using Umbraco 7.6.13 我正在使用Umbraco 7.6.13

Any help greatly appreciated. 任何帮助,不胜感激。

Thanks 谢谢

Have something similar but used with Surface Controller not Web API controller. 有类似的东西,但与Surface Controller而非Web API控制器一起使用。

Override HandleUnauthorizedRequest to implement custom response / override Umbraco & .NET defaults. 覆盖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"));
    }

It's odd that Forms authentication seems to be kicking in and redirecting you to login page for an API request. 奇怪的是,Forms身份验证似乎开始生效,并将您重定向到API请求的登录页面。 The AuthorizationFilterAttribute should return a Http 401 by default (so could deal with via web.config customErrors or httpErrors sections instead of code). 默认情况下, AuthorizationFilterAttribute应该返回Http 401(因此可以通过web.config customErrorshttpErrors部分代替代码来处理)。

May want to review your web.config settings? 可能想查看您的web.config设置?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM