how to redirect from http to https with suave, in f#

60 views Asked by At

How can I redirect a connection from http to https using Suave?

at https://gist.github.com/ademar/f4ddb788162dbdd9e104574e2accf07f I found this:

let redirectToSsl : WebPart =
      context(fun c ->
       match c.request.header "x-forwarded-proto" with
        | Choice1Of2 "http" ->
              let uriBuilder = new UriBuilder(
                                      Scheme = Uri.UriSchemeHttps,
                                      Path = c.request.path,
                                      Host = c.request.host)
              Redirection.redirect (uriBuilder.Uri.ToString())
        | _ -> fun _ ->async { return None })

but I am not really sure where that would fit in the pipeline?

1

There are 1 answers

0
Brian Berns On

I would change two things:

  • Check for the actual protocol. I think that x-forwarded-proto is only used for proxies, but I'm not certain.
  • To fit it into your pipeline, accept a webpart to invoke when the access is secure.

Result looks like this:

let redirectToSsl allow : WebPart =
    context (fun c ->
        if c.request.binding.scheme.secure then
            allow
        else
            let uriBuilder =
                new UriBuilder(
                    Scheme = Uri.UriSchemeHttps,
                    Path = c.request.path,
                    Host = c.request.host)
            Redirection.redirect (uriBuilder.Uri.ToString()))

Usage looks like this:

let app = redirectToSsl Files.browseHome   // allow browsing under SSL only

Caveat: I haven't tried this in practice, so there could be other issues I'm overlooking.