public
Last active

RequireHttpsAttribute using X-Forwarded-Proto header

  • Download Gist
RequireHttpsAttribute.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
using System;
using System.Web.Mvc;
using RequireHttpsAttributeBase = System.Web.Mvc.RequireHttpsAttribute;
 
namespace AppHarbor.Web
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true,
AllowMultiple = false)]
public class RequireHttpsAttribute : RequireHttpsAttributeBase
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
 
if (filterContext.HttpContext.Request.IsSecureConnection)
{
return;
}
 
if (string.Equals(filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"],
"https",
StringComparison.InvariantCultureIgnoreCase))
{
return;
}
 
if (filterContext.HttpContext.Request.IsLocal)
{
return;
}
 
HandleNonHttpsRequest(filterContext);
}
}
}

How about asp.net web api?
a custom RequireHttpsAttribute that also takes into consideration the "X-Forwarded-Proto" Header is also needed.
Correct?

Just what the doctor ordered! Thanks for sharing!

We have just had to come to this and had to do a FirstOrDefault() when checking the headers...

string.Equals(request.Headers["X-Forwarded-Proto"].FirstOrDefault(), "https", StringComparison.InvariantCultureIgnoreCase)

Here's a quick gist containing a similar version for requiring HTTPS on Web API calls for AppHarbor:

https://gist.github.com/geersch/7710361

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.