Skip to content

Instantly share code, notes, and snippets.

@runesoerensen
Created April 12, 2011 16:40
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save runesoerensen/915869 to your computer and use it in GitHub Desktop.
Save runesoerensen/915869 to your computer and use it in GitHub Desktop.
RequireHttpsAttribute using X-Forwarded-Proto header
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);
}
}
}
@ignaciofuentes
Copy link

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

@coachrob
Copy link

coachrob commented Apr 2, 2013

Just what the doctor ordered! Thanks for sharing!

@Jamadan
Copy link

Jamadan commented Apr 12, 2013

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)

@geersch
Copy link

geersch commented Nov 29, 2013

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

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

@RobertVandenberg
Copy link

I suggest using Uri.UriSchemeHttps instead of "https" directly.

http://msdn.microsoft.com/zh-tw/library/system.uri.urischemehttps(v=vs.110).aspx

@dahlbyk
Copy link

dahlbyk commented Jun 15, 2016

Also, StringComparison.OrdinalIgnoreCase would be more correct for the header check.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment