From HTTP to HTTPS and back (continued discussion)

by APIJunkie 27. March 2008 23:58

A couple of weeks ago I showed an easy way to redirect from HTTP to HTTPS.

Fosiul raised the issue that once you redirect to HTTPS all the pages become secure even the ones we do not need to be secure.

This can lead to some problems like adding additional stress on the web server machine.

To solve this problem we should be able to switch from https to http when ever we detect a page where we do not need secure communications.

One way to do that is to have a function that knows to switch both ways.

Example:

// set protocol to secure or unsecured according to bSecure flag.

// bSecure flag = true -> secure connection

// bSecure flag = false -> unsecured connection

public void setSecureProtocol(bool bSecure)

{

string redirectUrl = null;

// if we want HTTPS and it is currently HTTP

if (bSecure && !Request.IsSecureConnection) redirectUrl = Request.Url.ToString().Replace("http:", "https:");

else

// if we want HTTP and it is currently HTTPS

if (!bSecure && Request.IsSecureConnection) redirectUrl = Request.Url.ToString().Replace("https:", "http:");

//else

// in all other cases we don't need to redirect

// check if we need to redirect, and if so use redirectUrl to do the job

if(redirectUrl!=null)

Response.Redirect(redirectUrl);

}

One way to use the above function is in the page load handler of pages where a transition to or from HTTP or HTTPS should occur.

Putting the function call in the page load handler would make sure that a transition from secure to non secure and vice versa would occur before the rest of the page gets rendered.

Example:

protected void Page_Load(object sender, EventArgs e)

{

// set to HTTPS secure protocol

setSecureProtocol(true);

/// rest of code goes here

/// we will only reach this code in secure mode

}

If you want to be fancier you can use a custom HTTP module to detect and redirect using a variant of the setSecureProtocol function.

Example:

/// <summary>

/// HttpToHttpsRedirector - an http module to detect and redirect from http to https and vice versa

/// </summary>

public class HttpToHttpsRedirector: IHttpModule

{

 

public void Init(HttpApplication context)

{

context.BeginRequest +=
new System.EventHandler(Application_BeginRequest);

}

 

// your BeginRequest event handler.

private void Application_BeginRequest(Object source, EventArgs e)

{

HttpApplication application = (HttpApplication)source;

HttpContext context = application.Context;

// This is where your web site logic should decide if to redirect to http/https.

// The example code below always redirects to https!!!

if (true) setSecureProtocol(context, true);

}

public void Dispose()

{

}

// utility functions

// set protocol to secure or unsecure acording to bSecure flag.

// bSecure flag = true -> secure connection

// bSecure flag = false -> unsecure connection

public void setSecureProtocol(HttpContext context, bool bSecure)

{

string redirectUrl = null;

// if we want HTTPS and it is currently HTTP

if (bSecure && !context.Request.IsSecureConnection) redirectUrl = context.Request.Url.ToString().Replace("http:", "https:");

else

// if we want HTTP and it is currently HTTPS

if (!bSecure && context.Request.IsSecureConnection) redirectUrl = context.Request.Url.ToString().Replace("https:", "http:");

//else

// in all other cases we don't need to redirect

// check if we need to redirect, and if so use redirectUrl to do the job

if (redirectUrl != null)

context.Response.Redirect(redirectUrl);

}

}

Good luck!

Tags:

.NET | Web Development

Comments

3/28/2008 12:42:07 AM #

trackback

Trackback from DotNetKicks.com

From HTTP to HTTPS and back (continued discussion)

DotNetKicks.com

3/28/2008 1:17:43 AM #

fosiul

Hi, thanks for quick response and write another programm.
Actually i am new in asp.net, so will you please exlain me one thing please. here i am interested your custom http module solutions.

after creating HttpToHttpsRedirector class,i understand that, i will have to pass value which is setSecureProtocol(true) to this class, is that right ?

but how i will pass this value   ?? i understand that i will have to call this HttpToHttpsRedirector  class to everypage to pass this value, is this right ?? if yes, i will do that ?
Please advise.

Last thing : if i just copy code and past it to "HttpToHttpsRedirector.vb" will it work ?? or do i have to edit aswell ?

Thanks in advance

fosiul United Kingdom

3/28/2008 1:19:44 AM #

fosiul

One more thing, can i get a code which is written by Vb.net ( i just noticed, you wrote code by C#)
it would realy help me.

fosiul United Kingdom

3/28/2008 3:55:48 AM #

Chris

I have been using Sanibel Logic's SSLRedirect (www.sanibellogic.com/.../Products.aspx with great success.  Sure it cost a little bit of money ($40.00) but it's a clean implementation and supports regular expression matching on the query string.  The latest version even supports IIS 7 Integrated Pipeline.

Have a look and see if this works for you...

Chris United States

3/28/2008 10:09:37 AM #

APIJunkie

Fosiul,
To learn more about creating custom HTTP modules you can check out the tutorial at msdn2.microsoft.com/.../ms227673(VS.80).aspx
To convert code from C# to VB.NET you can use an online code converter like the one at labs.developerfusion.co.uk/.../csharp-to-vb.aspx

APIJunkie United States

3/28/2008 10:12:06 AM #

APIJunkie

Thanks Chris,
I will have a look.

APIJunkie United States

3/28/2008 10:13:03 AM #

fosiul

Hi, thanks again.
i have already converted your code to vb.net.

One last  thing you have not answered yet, but which i think is important for this code.

to work with your code, i have to sent request from the page i want to secure. i will have to sent setSecureProtocol = true or false to HttpToHttpsRedirector class. but i am unable to do that.
i tried with following code from web page :

Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Session("RedirectHttps") = True
End Sub

but at httpmodule , void Application_BeginReques sections, it always getting null value,( if (true) setSecureProtocol(context, true)) its unable to get the value i am sending from web page, my understanding here is,

The HttpModule.Application_BeginRequest happens before the Page_Init, so I can't set anything in the page that would be recognized by the module.

thats why i dont  understand, how i will sent value from web page to HttpToHttpsRedirector class ?

Hope it make sense . waiting for the reply, and thanks again.

fosiul United Kingdom

4/10/2008 2:30:49 AM #

fosiul

HI, i just want to submit a link for full tutorial of this post.

http://fosiul.co.uk/subcategory.aspx?Id=88

only problem here is, you gave one part of the solutions, but there are lot of other things need to implement your code which for a new commer to asp.net like me would be  problem.

Hope this will help to other.
Thanks for your nice post.

fosiul United Kingdom

2/19/2009 9:32:17 PM #

Sedgar

// If page accessed via non SSL and its not localhost then redirect to SSL.
if (!this.Request.IsSecureConnection && !this.Request.IsLocal)
{
  // build secure Url based on request
  UriBuilder secureUriBuilder = new UriBuilder(this.Page.Request.Url);
  secureUriBuilder.Scheme = Uri.UriSchemeHttps;
  // use ssl port from configaration file
  secureUriBuilder.Port = ConfigurationHelper.PortSSL;

  // Redirect to secure page if need
  Response.Redirect(secureUriBuilder.ToString());
}

Sedgar Ukraine

Comments are closed

About the author

Name of author

I was first wounded by x86 assembly, recovered and moved on to C. Following a long addiction to C++ and a short stint at rehab I decided to switch to a healthier addiction so I am now happily sniffing .NET and getting hooked on Silverlight.

I am mainly here to ramble about coding, various API’s, Junkies(me especially) and everything else that happens between coders and their significant other.

  James Bacon