Last active
April 28, 2016 22:26
-
-
Save haydosw/fc5c7ec8b44dcabcf3bf to your computer and use it in GitHub Desktop.
Force SSL-Always for NancyFx requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AlwaysUseHttps : IApplicationStartup | |
{ | |
private readonly IConfigurationService _config; | |
public AlwaysUseHttps(IConfigurationService config) | |
{ | |
_config = config; | |
} | |
public void Initialize(IPipelines pipelines) | |
{ | |
pipelines.BeforeRequest.AddItemToStartOfPipeline(RedirectIfNotHttps); | |
} | |
private Response RedirectIfNotHttps(NancyContext context) | |
{ | |
var requestUrl = context.Request.Url.Scheme; | |
if ("https".Equals(requestUrl, StringComparison.OrdinalIgnoreCase)) | |
{ | |
// We are ssl continue pipeline | |
return null; | |
} | |
return RequiresHttps(context); | |
} | |
private Response RequiresHttps(NancyContext context) | |
{ | |
var request = context.Request; | |
if (request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase) == false) | |
{ | |
return new Response { StatusCode = HttpStatusCode.Forbidden }; | |
} | |
var redirectUrl = request.Url.Clone(); | |
redirectUrl.Port = _config.HttpsPort; | |
redirectUrl.Scheme = "https"; | |
return new RedirectResponse(redirectUrl.ToString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment