Reputation: 411
How can I require HTTPS for my C# apicontrollers?
I know that I can add a RequireHTTPSAttribute like this here : http://www.asp.net/web-api/overview/security/working-with-ssl-in-web-api but this just adds "HTTPS Required" to the response.
What I would rather have it do, is output json on screen that says, "HTTPS Required" instead of it just being on what of the response headers.
Is this possible?
EDIT
This is what I came up with, is there a more elegant way to do it, so I have less repetition of code.
ResultWrapper<Temp> wrapper = new ResultWrapper<Temp>(Request);
if (Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
wrapper.Error = "Https is Required";
}
else
{
wrapper.RequestUrl = Request.RequestUri.ToString();
wrapper.Results.Url = "http://www.google.com";
}
return wrapper;
Second Edit
I found a better way, you can edit the Content stream being sent back in the response and send back any class you want serialized as Json, like this :
Content = new StringContent(Json.Encode(wrapper))
Upvotes: 2
Views: 4911
Reputation: 152
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);
}
}
Upvotes: 2