Web API 2 RequireHttps allowing http connection

别等时光非礼了梦想. 提交于 2020-01-15 03:05:55

问题


I have created the following action in my MVC Web API 2 controller:

    [ResponseType(typeof(int))]
    [RequireHttps]
    public IHttpActionResult SaveLead(EcommerceLead lead)
    {
    }

But in my test app I am making a call to

http://localhost/api/savelead

And it is working. Is there any way to make the action to only work if it is called over https, ie return a 404 if it isn't or something?


回答1:


If you are using RequireHttps from Mvc namespace, it will not work with Web API. You can write a simple filter for Web API yourself to enforce HTTPS. Since you are using Web API 2, create an authentication filter like this.

public class RequireHttpsAttribute : IAuthenticationFilter
{
    public bool AllowMultiple
    {
        get { return true; }
    }

    public Task AuthenticateAsync(HttpAuthenticationContext context, 
                                        CancellationToken cancellationToken)
    {
        if (context.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            context.ActionContext.Response = new HttpResponseMessage(
                                    System.Net.HttpStatusCode.Forbidden);

        }
        return Task.FromResult<object>(null);
    }

    public Task ChallengeAsync(HttpAuthenticationChallengeContext context,
                                        CancellationToken cancellationToken)
    {
        return Task.FromResult<object>(null);
    }
}



回答2:


You can use Message Handler.

public class RequireHttpsHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "HTTPS Required"
});
}
return base.SendAsync(request, cancellationToken);
}
}



回答3:


If you are using web api older version you can use Authoriztion filter.

public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
            {
                ReasonPhrase = "HTTPS Required"
            };
        }
        else
        {
            base.OnAuthorization(actionContext);
        }
    }
}


来源:https://stackoverflow.com/questions/26504409/web-api-2-requirehttps-allowing-http-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!