tags:

views:

83

answers:

2

When should I enforce SSL for secure pages in an ASP.NET page life-cycle?

I mean should I do it inside page_load? or OnInit? or some other function?

I am using the following code to enforce SSL for certain pages, but where should I put this code? Earlier I placed it inside OnInit function, but that did not work well with ASP.NET wizards. Do I need to check whether it's postback or not first?

 if (!HttpContext.Current.Request.IsSecureConnection) {
                HttpContext.Current.Response.Redirect(SiteNavigation.ResolveAbsoluteUrl(true, HttpContext.Current.Request.Url.PathAndQuery));
            }
A: 

If you're going to redirect the user, you want to do it as early in the life cycle as possible, since any cpu spent on the lifecycle will be wasted. Do the redirect in OnInit.

Ken Mason
-1 The question says that he tried OnInit and it did not work well.
Gonzalo
It works fine, actually. The tricky part is that the designer may try to remove it, since OnInit is in the auto-generated code block usually. Just make sure that you add the code back in when VS tries to remove it. It's pretty simple :)
Ken Mason
A: 

The other option would be to do it outside the application altogether and enforce SSL in IIS if the SSL connection is required for the entire site. We've done this in IIS6 by creating two sites for the same domain name.

mysite.com:80 has an HTTP 403 redirect to the SSL version of the site. mysite.com:443 has the actual application in which SSL is enforced.

If the SSL connection isn't required for the whole site, but just the login page or some other isolated part of the site than the programatic method in Global.asax (mentioned by Gonzalo) is probably the best way to go since that'll catch it very early in the page lifecycle.

kdmurray