Click here to Skip to main content
Click here to Skip to main content

Switching Between HTTP and HTTPS Automatically

By , 7 Jul 2005
 

Automatic Protocol Switching

Important: New Version

Please refer to the new version of this module and article here: Switching Between HTTP and HTTPS Automatically: Version 2.

Introduction

Let's face it. Providing sensitive information on a web site is a risk. Many visitors will not give out that kind of data even if they see that the web site claims security. Many more will certainly not reveal their personal details if the warm-and-fuzzy closed padlock isn't visible in their browser window.

Background

Enter Secure Sockets Layer. SSL is a developer's tool for securing the transmission of data. Whether you are encrypting pages for the checkout area of an e-commerce site or you are protecting the personal statistics that your users supply you for marketing; SSL is ideal. A trusted certificate installed on the web server offers visitors, that good feeling of a secure environment.

There are caveats when implementing a web site that makes use of the HTTPS protocol. I'm not referring to the technical nuances you, or a system administrator, must face when installing a certificate on the server. What about simply adding a link from one page to another page that should be secured?

Those of you who have experience with writing web pages that use SSL probably know where I'm going with this. You cannot switch protocols unless you provide an absolute URL. Therefore, in order to allow a visitor to click on a link that should take them to a secure web page, the reference must be absolute.

https://www.codeproject.com/secure/getsensitiveinfo.asp

To make things worse, many browsers download pages referenced by a relative URL with the same protocol as the last request. So, if you had a link in the above file to another page in the root directory, that you wanted to show with the HTTP protocol, it would also have to be absolute.

<!--
The following will actually be translated as 
https://www.codeproject.com/welcome.asp;
thus, retaining the HTTPS protocol that was last used.
-->
<a href="../welcome.asp">Back to the Welcome Page.</a>

Generally, it is not a good idea to encrypt every single page request with SSL. It makes for slower page serves and more bandwidth usage. It is also more intensive on the server's CPU; something your hosting provider may not be pleased with.

A Solution

Being forced to use absolute URLs for internal links in a web site is less than appealing. The next thing you know, the web site's domain name changes (for any number of reasons) or you have a staging server, which means you have to maintain a separate copy of the site for that set of absolute URLs. It makes much more sense to mark certain files and/or entire directories as "secure". This would allow you the benefit of using relative URLs freely within your web pages. If an existing page needs to be made secure, you simply add it to the list of marked files instead of finding and replacing all links to the page with an absolute URL.

That's where SecureWebPageModule comes in. SecureWebPageModule is a class that implements the IHttpModule interface. HTTP modules give programmers a means of "attaching" to a web application to process its events. It's like descending from the System.Web.HttpApplication class and overriding the application and session events in a Global.asax file. The main difference is you don't have to worry about copying and pasting the same code into the file for every application that is to use it. HTTP modules are simply "linked in" to a web application and become part of the pipeline.

The goal of this security solution is to allow a developer to easily secure a web site without the need to hard-code absolute URLs. This is accomplished by listing the files and/or directories that should be secured by SSL. It only seems natural to have a custom configuration section for this.

Configuration

Simply add a new section to the web.config file of the application to secure. Make sure you add this section outside of the <system.web> section but inside the <configuration> tags. The <secureWebPages> section has one optional attribute: enabled. Include the enabled attribute with a value of true or false. The default value is true which enables the automatic web page security module. Setting this attribute to false indicates that you want the feature disabled. This is ideal for testing on a machine that doesn't have a certificate installed (like your development machine).

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    ...
    <secureWebPages enabled="true">
        ...
    </secureWebPages>
    ...
    <system.web>
        ...
    </system.web>
</configuration>

Next, you need to specify any files and directories to include for automatic security. Files are added via <file> tags. Directories are added with <directory> tags. Both tags require a path attribute. The path attribute should be a relative path to the file or directory that will be processed by the security module. In addition, both tags may include an optional attribute: ignore. Set the ignore attribute to either true or false. The default value is false, signifying that the file or directory should be secured. If you set this attribute to true, the security module will not change a request for that file or a file in that directory.

What does that mean? All application requests are processed by the SecureWebPageModule, when enabled. If the requested file is specified in a <file> tag or it is in a directory that is specified in a <directory> tag of the <secureWebPages> section, it is served to the client securely. That is, the response is redirected to the requested file with the HTTPS protocol if it is not already requested as such. If a request does not have a matching entry in the <secureWebPages> section, the response is redirected to the requested file with the HTTP protocol if it was not requested as such. The only exceptions are requests that are matched with a <file> or <directory> tag that has its ignore attribute set to true. In that case, no protocol switch is performed.

    ...
    <secureWebPages enabled="true">
        <file path="Login.aspx" />
        <file path="Lib/PopupCalendar.aspx" ignore="True" />
        <file path="Members/ViewStatistics.aspx" />
        <directory path="Admin" />
        <directory path="Members/Secure" />
    </secureWebPages>
    ...

The above example enables the SecureWebPageModule that is linked to the accompanying web application. As a visitor clicks links and maneuvers through the web site, the SecureWebPageModule processes each request. If the user requests a file located in the Admin or Members/Secure directories, the request is automatically served with the HTTPS protocol. A request to any file in the root directory, except for Login.aspx, is served via the HTTP protocol regardless of the previous request. Files in the Members directory, other than Members/ViewStatistics.aspx, use HTTP. In the case of Login.aspx and Members/ViewStatistics.aspx, HTTPS is used. Finally, if a client requests the PopupCalendar.aspx file in the Lib directory, the file is served exactly as it was requested.

The developer may have chosen to ignore the Lib/PopupCalendar.aspx file because that page is used by several other pages that have calendar icons which, when clicked, opens a pop-up window to the page, allowing the user to select a date. If one of these icons is clicked on a page that is not secure, the developer wouldn't want the Lib/PopupCalendar.aspx page to be served with SSL. On the other hand, if a calendar icon was clicked on a page in the Admin directory, the developer certainly would not want the Lib/PopupCalendar.aspx page to be presented via HTTP. The user would, most likely, be alerted by their browser that they were leaving a secure area to view the pop-up page. I think I can safely state that most users would lose any feeling of comfort after seeing a warning like that.

The SecureWebPageSectionHandler Class

The SecureWebPageSectionHandler class is extremely important to the SecureWebPageModule class. SecureWebPageModule relies on this class to handle parsing of the <secureWebPages> configuration section in your application's web.config file. This class implements IConfigurationSectionHandler. It provides an implementation of the Create method. This method is implemented by handlers to parse the XML of the configuration section. Please download the source code to see all of the classes used in this solution.

    public object Create(object parent, object configContext, 
       XmlNode section)
    {
        // Create a SecureWebPageSettings object for the settings 
        // in this section
        SecureWebPageSettings Settings = new SecureWebPageSettings();

        // Get the enabled attribute
        if (section.Attributes["enabled"] != null)
        {
            Settings.Enabled = (section.Attributes["enabled"].Value.ToLower()
                   != "false");
        }

        if (Settings.Enabled)
        {
            // Traverse the child nodes
            SecureWebPageCollection SecurePathList;
            string Path;
            bool Ignore;
            foreach (XmlNode Item in section.ChildNodes)
            {
                if (Item.NodeType == System.Xml.XmlNodeType.Comment)
                    // Skip comment nodes (thanks to dcbrower
                    // on CodeProject for pointing this out)
                    continue;
                else if (Item.Name.ToLower() == "directory")
                    // This is a directory path node
                    SecurePathList = Settings.SecureDirectories;
                else if (Item.Name.ToLower() == "file")
                    // This is a file path node
                    SecurePathList = Settings.SecureFiles;
                else
                    // Throw an exception for this unrecognized node
                    throw new SecureWebPageSectionException(string.Format(
                        "'{0}' is not an acceptable setting.", 
                        Item.Name), Item);
            
                // Get the path attribute value
                if (Item.Attributes["path"] != null && 
                    Item.Attributes["path"].Value.Trim().Length > 0)
                {
                    // Get the value of the path attribute
                    Path = Item.Attributes["path"].Value.Trim();

                    // Add leading and trailing "/" characters where needed
                    if (Path.Length > 1)
                    {
                        if (!Path.StartsWith("/"))
                            Path = "/" + Path;
                        if (SecurePathList == Settings.SecureDirectories 
                             && !Path.EndsWith("/"))
                            Path += "/";
                    }

                    // Check for an ignore attribute
                    if (Item.Attributes["ignore"] != null)
                        Ignore = (Item.Attributes[
                           "ignore"].Value.Trim().ToLower() == "true");
                    else
                        Ignore = false;

                    // Add the item to the collection
                    SecurePathList.Add(new SecureWebPageItem(Path, Ignore));
                }
                else
                    // Throw an exception for the missing Path attribute
                    throw new SecureWebPageSectionException(
                       "'path' attribute not found.", Item);
            }
        }

        // Return the settings
        return Settings;
    }

This method parses the XML of the <secureWebPages> section and stores the information in an instance of the SecureWebPageSettings class. The SecureWebPageSettings class contains properties for the enabled attribute and collections for the directories and files to secure as specified in the configuration section. Each item of the collections is represented by the SecureWebPageItem class, which defines properties for the path and ignore attributes of each <file> and <directory> tag.

The SecureWebPageModule Class

The SecureWebPageModule class is an implementation of the IHttpModule interface. IHttpModule defines two methods that must be implemented. The first is the Dispose method. No resources are being used in this implementation; therefore, the method is empty.

    public void Dispose()
    {
        // No resources were used.
    }

The second method is the Init method. This method is implemented to initialize the module. In this case, it "hooks" into the application's BeginRequest event.

    public void Init(HttpApplication Application)
    {
        // Add a reference to the private Application_BeginRequest 
        // handler to the application's BeginRequest event
        Application.BeginRequest += (new EventHandler(
             this.Application_BeginRequest));
    }

Finally, the BeginRequest event handler processes each request of the application.

    private void Application_BeginRequest(Object source, EventArgs e) 
    {
        // Get the settings for the secureWebPages section
        SecureWebPageSettings Settings = 
            (SecureWebPageSettings)ConfigurationSettings.GetConfig(
                 "secureWebPages");

        if (Settings != null && Settings.Enabled)
        {
            // Cast the source as an HttpApplication instance
            HttpApplication Application = (HttpApplication)source;

            // Get the relative file path of the current 
            // request from the application root
            string RelativeFilePath = 
                Application.Request.Url.AbsolutePath.Remove(
                0, 
                Application.Request.ApplicationPath.Length).ToLower();
            if (!RelativeFilePath.StartsWith("/"))
                // Add a leading "/"
                RelativeFilePath = "/" + RelativeFilePath;

            // Intialize the flags
            bool MakeSecure = false;
            bool Ignore = false;

            // Determine if there is a matching file path for 
            // the current request
            int i = Settings.SecureFiles.IndexOf(RelativeFilePath);
            if (i >= 0)
            {
                MakeSecure = true;
                Ignore = Settings.SecureFiles[i].Ignore;
            }

            // Try to find a matching directory path, if no file was found
            i = 0;
            while (!MakeSecure && i < Settings.SecureDirectories.Count)
            {
                MakeSecure = RelativeFilePath.StartsWith(
                    Settings.SecureDirectories[i].Path.ToLower());
                Ignore = Settings.SecureDirectories[i].Ignore;
                i++;
            }

            // Test for the ignore flag
            if (!Ignore)
            {
                // Request a secure/unsecure page as needed
                if (MakeSecure)
                    SSLHelper.RequestSecurePage();
                else
                    SSLHelper.RequestUnsecurePage();
            }
        }
    }

The event handler retrieves the SecureWebPageSettings from the configuration settings. These settings are used to determine a course of action. If security is enabled, the application is used to build a relative path for the currently requested file. Next, the SecureFiles collection of the Settings object is searched for a match with the relative path of the current request. If no matching file was found, the SecureDirectories collection is traversed for a path that matches any parent directory of the current request. Lastly, the Ignore property of the matching item, if any, is tested. If no indication to ignore was present, the request is made as specified. The SSLHelper class is used to secure or "unsecure" a page request. The helper class simply replaces the current request's protocol and redirects the response, if needed.

Adding the Module to an Application

In order for a HTTP module to work with a web application, it must be added to the list of modules used. The machine.config file includes many modules for you. It's up to you to add any additional modules that you want to process your application(s). There are two ways you can add the module.

The first option you have, is to add the module to an individual application. This requires that you edit the web.config file of the application. You will need to add a custom configuration section handler for the <secureWebPages> section and a module addition to the <httpModules> section.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    ...
    <configSections>
        ...
        <section 
            name="secureWebPages" 
            type="Hyper.Web.Security.SecureWebPageSectionHandler, 
            WebPageSecurity" 
            allowLocation="false" />
    </configSections>
    
    ...
    
    <system.web>
        ...
        <httpModules>
            ...
            <add 
                name="SecureWebPage" 
                type="Hyper.Web.Security.SecureWebPageModule, 
                WebPageSecurity" />
        </httpModules>
        ...
    </system.web>
    ...
</configuration>

Your second option is to add the module to all web applications. You will need to make similar modifications to the machine.config file. Editing the machine.config file should only be performed by a knowledgeable person with "Administrator" privileges. Always make a backup of your machine.config file before editing it. If you choose to add the module and configuration section handler to your machine.config file, you should sign the assembly with a strong name and register it in the Global Assembly Cache (GAC). The AssemblyInfo.cs file provided with the project source should have a line near the bottom, that is commented to prevent signing the assembly. To sign the assembly during a compile, un-comment this line.

[assembly: AssemblyKeyFile(@"Key.snk")]

For more information on registering an assembly in the GAC, please refer to the .NET Framework documentation.

Points of Interest

This module was desperately needed for a project I was working on earlier in the year. The web site contained nearly 100 pages and controls in 7 main directories. Some of the directories under the root contained directories as well. It was going to be a nightmare to secure certain areas and pages with absolute URLs.

The ignore attribute and feature was not in my original design and implementation. Not until I implemented the module in the web site, did I see the need for it. The example I provided above, with the PopupCalendar.aspx page is exactly how I stumbled across the problem.

License

This article, along with any associated source code and files, is licensed under The BSD License

About the Author

Matt Sollars
Web Developer
United States United States
Member
I began programming on my Commodore 64 at around the age of 12. After migrating to DOS and then Windows, I decided to take on the Web. Several languages and platforms later, I have settled in with .NET nicely. I am currently the owner of a software consulting company and lead application developer for a learning-based technology consultation company.
 
The love of a finished application is usually at war with the desire to improve it as soon as it's released (they're never really finished).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membernasserbr4 Nov '12 - 23:44 
Thank you for this great article!
GeneralRe: My vote of 5memberMatt Sollars5 Nov '12 - 18:02 
You're welcome, but don't forget to check out a newer version of the article at: http://www.codeproject.com/aspnet/WebPageSecurity_v2.asp[^].
 
The project is also up to version 4 and hosted on Google Code at: https://code.google.com/p/securityswitch/[^]!

Matt

GeneralMy vote of 5memberHovik Melkomian18 Mar '12 - 4:04 
wonderful!!!
tnx
GeneralMy vote of 5memberthawawi25 Mar '11 - 12:14 
jj
Questionweb security only working as http://localhostmemberbobprosser29 Dec '10 - 10:50 
Just implemented Ventaur.WebSecurity as works great browsing as http://localhost on the IIS server. Doesn't work (not toggling bewteen http and https) when browsing by IP address or http://servername on the IIS server - what am I missing?
 
I've played with the bindings in IIS but no luck, any help appreciated.
AnswerRe: web security only working as http://localhostmemberMatt Sollars31 Dec '10 - 5:47 
Firstly, I highly recommend you upgrade this module to the latest version found via this new article:
www.codeproject.com/aspnet/WebPageSecurity_v2.asp[^]
 
Next, SSL certificates only work on a single host name (unless you purchase a wild card certificate, which will work on multiple). Therefore, the certificate you installed in IIS is likely only for a single host. If it is self-signed, it should work via https://servername. If you purchased one for a live domain (e.g. www.mysite.com), it will only work for that domain.
 
Does that help?

GeneralMy vote of 5memberthatraja5 Oct '10 - 23:34 
Good one...thanks
GeneralThank you!membersmunir78613 Sep '10 - 3:47 
This is really informative on ssl & good,
Thanks ... Thumbs Up | :thumbsup:
 
http://www.prepareuktest.co.uk[^]
GeneralDon't work with nonstandard portsmemberabragimovich11 May '10 - 1:42 
First of all i want to say thanks for pretty article.
 
But i found one bug. If IIS use TCP port different from 80, this solution doesn't work.
GeneralRe: Don't work with nonstandard portsmemberMatt Sollars12 May '10 - 8:05 
Thanks. That is a known bug with a workaround. Just set the unencryptedUri to your website's address including the port. Likewise, if you use a different port for SSL, set the encryptedUri accordingly.
<secureWebPages ... unencryptedUri="www.mywebsite.com:8080" encryptedUri="www.mywebsite.com:80443">
  ...

GeneralRe: Don't work with nonstandard portsmemberMatt Sollars12 May '10 - 8:07 
Also, please upgrade to the latest version. I have a much newer article with the newer versions of the code.
Switching Between HTTP and HTTPS Automatically: Version 2[^]

GeneralSSLmemberjanak Magotra5 May '10 - 17:50 
SSL Settings
GeneralLoad balancer SSL Offloadingmemberzvjerka2431 Aug '09 - 6:57 
Is this working in case SSL Offloading?
 
Actually we have load balancer and iis server is not running https itself. The load balancer uses https to communicate with client (browser) but uses http to the iis.
I tried to make some workaround but didn't make that.
 
It is not problem to me to implement your component in mine website, but to check this I must to deploy that on production. Because of that I'm asking you if this component is able to deal with this.
 
Please help!
 

Thank you,
Vladimir
GeneralRe: Load balancer SSL OffloadingmemberMatt Sollars31 Aug '09 - 10:14 
Hi Vladimir,
 
I cannot verify if this module works in your scenario. In theory, it will not work. The moment the load balancer requests a page via HTTP that should be secured, the website will issue a redirect back to the browser via HTTPS. The browser will then request the same page via HTTPS. Your load balancer will request the page via HTTP again from IIS and an infinite loop will ensue.
 
You would have to have your load balancer (reverse proxy) manage the rules of switching OR you can have it add a header to the request when sent to IIS. If you have it send a header, you could change the code of this module to not issue a redirect if that header is present.
 
Good luck!
 

Matt
www.geekfreeq.com
 
Help my dad get a Wii at MyDadNeedsAWii.com

GeneralRe: Load balancer SSL Offloadingmemberzvjerka2431 Aug '09 - 22:13 
Thank you Matt! Smile | :)
GeneralRe: Load balancer SSL OffloadingmemberMatt Sollars1 Sep '09 - 3:01 
You're welcome. In addition, if you do use this module in another scenario, I recommend you upgrade it to the latest version. There is a newer article due to all the changes from the original version.
 
Switching Between HTTP and HTTPS Automatically: Version 2[^]
 

Matt
www.geekfreeq.com
 
Help my dad get a Wii at MyDadNeedsAWii.com

General'ajaxcontroltoolkit' is undefinedmembermidavis21 Nov '08 - 5:15 
Once I try to go secure and use Ajax I get the following error. Is there a way to fix this?
GeneralRe: 'ajaxcontroltoolkit' is undefinedmemberMatt Sollars21 Nov '08 - 7:30 
Hello. Please, visit the newer article for this module (this one is outdated). The new version of the module has support for AJAX and other handlers. You'll have to read the new article for all the details on what is new/changed.
 
http://www.codeproject.com/aspnet/WebPageSecurity_v2.asp[^]
 

Matt

Help my dad get a Wii at MyDadNeedsAWii.com

GeneralMay be silly.. but I am not sure whether it is working or not!!membervishnuvvn28 Oct '08 - 3:03 
Hi Matt,
 
I tried to work around with my sample site.. I loaded the dll file, setup the web.config.. but when I browsed login.aspx which is https, the address bar is not showing https... it still just showin as http. I am not getting any errors but how to make sure its workin in my localhost?
 
Thanks,
 
Vishnu

GeneralRe: May be silly.. but I am not sure whether it is working or not!!memberMatt Sollars21 Nov '08 - 7:26 
The sample site assumes you are working locally with no certificate and attempts to visually let you know that the module is switching for certain pages.
 
In order to actually test the module on your localhost, you will need to set the secureWebPages mode to "On" (instead of "RemoteOnly") and install an SSL certificate in IIS. You can use a self-signed certificate to avoid having to pay for one that you can only use for testing. Please, search this forum or the Net on how to create a self-signed certificate for your version of IIS.
 
You can always skip the certificate part and take note of the address bar as you test. Odds are you will get server errors when the module redirects you to HTTPS without a certificate installed, but at least you can see it's working.
 
Good luck!
 

Matt

Help my dad get a Wii at MyDadNeedsAWii.com

GeneralRe: May be silly.. but I am not sure whether it is working or not!!membervishnuvvn21 Nov '08 - 7:29 
Hi Matt,
 
I think we have resolved this issue long back.. in other forum.. Anyways its working very fine now..
 

Thanks,
 
Vishnu

GeneralRe: May be silly.. but I am not sure whether it is working or not!!memberMatt Sollars21 Nov '08 - 7:29 
Vishnu,
 
Also, please update to the latest version of the module. This article is outdated and a newer one exists here:
 
http://www.codeproject.com/aspnet/WebPageSecurity_v2.asp[^]
 

Matt

Help my dad get a Wii at MyDadNeedsAWii.com

GeneralRedirectFromLoginPage method of forms authentication failed to redirect to originally requested pagememberPranjaliBhide29 Sep '08 - 21:00 
I developed a site with a reserved section based on roles, when I try to access that page i got redirected correctly to the loginpage and on the address bar i see
the ReturnUrl containig the address to point to:
 
http://localhost/SiteName/login.aspx?ReturnUrl=%2fSiteName%
2fadministrator%2fdefault.aspx
 
administrator/default.aspx is the page I have to reach
I authenticate succesfully but when the following instruction executes without error:
FormsAuthentication.RedirectFromLoginPage(user, chkRemember.Checked)
i still remain in the same page, only user and pwd disappear
 
the address in the bar is still the same....
 
otherwise if i submit incorrect user o pwd I got an error that indicates the redirect correctly fails:
If AuthenticateUser(userEncoded, pwdEncoded, roles) Then
FormsAuthentication.RedirectFromLoginPage("@" & ruoli, chkRemember.Checked)
 
Else
lblLogin.Text = "Access denied!"
End If
 

Any idea?
 
Thanks,
In Advance.
GeneralRe: RedirectFromLoginPage method of forms authentication failed to redirect to originally requested pagememberMatt Sollars30 Sep '08 - 2:38 
It sounds like the user is getting authenticated, but the page indicated in ReturnUrl is set to deny access to that user or role. Do you have an <authorization> section in your root web.config or in a web.config file that is in the administrator directory? If so, what does that section look like? Also, are you using any of the built-in membership and role providers or custom implementations?
 

Matt

Help my dad get a Wii at MyDadNeedsAWii.com

GeneralRe: RedirectFromLoginPage method of forms authentication failed to redirect to originally requested pagememberfeeling_good4 May '09 - 6:45 
I have this problem too.
It happens when using default membership but also custom membership.
One workaround is to set requireSSL="false" in web.config.
 

<forms requireSSL="false" />

 
Any solution besides this workaround?
GeneralRe: RedirectFromLoginPage method of forms authentication failed to redirect to originally requested pagememberfeeling_good4 May '09 - 7:04 
I've noticed that I posted on Version_1 but this also happens in v3.1.
Thanks.
GeneralRe: RedirectFromLoginPage method of forms authentication failed to redirect to originally requested pagememberMatt Sollars4 May '09 - 8:23 
This is a dilemma I am still considering a solution for. I originally handled requests with the application's BeginRequest event. However, that caused problems with cookie-less session processing, because the session ID is not generated until just before the AcquireRequestState event (which is where I hook the module into now).
 
I suppose the best solution would be to detect if you are using cookie-less sessions and attach to the proper event based on that condition. At about line 47 of the SecureWebPageModule.cs code file, this line...
context.AcquireRequestState += new EventHandler(this.Application_ProcessRequest);
...should become this block...
if (IsCookielessSessionUsed(context)) {
    // This ensures that the session ID is available for cookie-less session processing.
    context.AcquireRequestState += new EventHandler(this.Application_ProcessRequest);
} else {
    context.BeginRequest += new EventHandler(this.Application_ProcessRequest);
}
...with this new method added to the class.
protected bool IsCookielessSessionUsed(HttpApplication context) {
    string VirtualPath = context.Request.Path;
    string ModifiedPath = context.Response.ApplyAppPathModifier(VirtualPath);
    return !ModifiedPath.Equals(VirtualPath);
}
I have not tested this solution, but it has good potential to fix the issue in most cases. There are some edge cases that should be accounted for, but you can try this fix and see if it works for your scenario.
 
Good luck!
 

Matt

Help my dad get a Wii at MyDadNeedsAWii.com

GeneralRe: RedirectFromLoginPage method of forms authentication failed to redirect to originally requested pagememberfeeling_good4 May '09 - 22:13 
Hello,
 
Now I get "Request is not available in this context" exception when IsCookielessSessionUsed is called.
 
Thanks
GeneralRe: RedirectFromLoginPage method of forms authentication failed to redirect to originally requested pagememberfeeling_good5 May '09 - 1:36 
Hello again,
 
I´ve tried EndRequest event instead of AcquireRequestState and the problem still occurs so I think that the problem is not in AcquireRequestState event.
GeneralRe: RedirectFromLoginPage method of forms authentication failed to redirect to originally requested pagememberMatt Sollars5 May '09 - 3:23 
I forgot that the core objects (e.g. Response, Request, etc.) are not available during the Init stage. The only way to detect if cookie-less sessions are used is to wait until BeginRequest. So, something like this may be a better option than the lines I sent earlier.
// Hook into the BeginRequest event in order to test for cookie-less sessions.
context.BeginRequest += new EventHandler(Application_BeginRequest);
Another method is needed for the decision of when to process.
private void Application_BeginRequest(object sender, EventArgs e) {
    HttpApplication Context = sender as HttpApplication;
    if (Context != null) {
        if (IsCookielessSessionUsed(Context)) {
            // This ensures that the session ID is available for cookie-less session processing.
            Context.AcquireRequestState += new EventHandler(Application_ProcessRequest);
        } else {
            // Process the request here.
            Application_ProcessRequest(sender, e);
        }
    }
}
Unfortunately, this is all about timing. When certain contexts are available for querying and when it is too late to redirect the user.
 
If the above does not work for you, you can always change "AcquireRequestState" to "BeginRequest" in the original Init method's implementation. It should work for you then, as long as you do not use cookie-less sessions. I'll think up a better solution in the future.
 
Thanks for your input.
 

Matt

Help my dad get a Wii at MyDadNeedsAWii.com

GeneralRe: RedirectFromLoginPage method of forms authentication failed to redirect to originally requested pagememberMatt Sollars18 May '09 - 6:49 
I did some more research on this problem, and you were correct; the issue was not with the timing of the application event handler. Setting <forms requireSSL="true"... /> tells ASP.NET that it can only retrieve the user's authentication ticket (a session cookie) via SSL. If the user requests a page that is not secured by SSL, the ticket is not sent to the server, and the application assumes the user is not authenticated. If that page requires an authenticated user, the application redirects the user back to the login page and a vicious cycle can ensue.
 
There are only 2 solutions to this problem. The first is to not require SSL for the forms authentication module; thus, allowing the authentication ticket to be sent over standard HTTP. The second solution is to secure every single page that requires an authenticated user. This module can be used for the second option. However, please note that even if you have a page that does not require authentication, but perhaps displays the user's name if they are logged in (e.g. the LoginName control on a master page), that page will not think the user is logged in unless it is access via HTTPS.
 
In a case where login controls are used on every page, requiring SSL will require securing the entire website with this module. You can do that quite easily, but everything will be encrypted then. Your server's CPU and bandwidth will be used a bit more heavily.
 

Matt
www.geekfreeq.com
 
Help my dad get a Wii at MyDadNeedsAWii.com

GeneralRe: RedirectFromLoginPage method of forms authentication failed to redirect to originally requested pagememberfeeling_good18 May '09 - 7:46 
Yes that's exactly the problem I am facing and I have to encrypt allthe website.
I'll try to do some reasearch on the subject when I have more time, and if I find something usefull I'll let you know.
Thanks.
GeneralRe: RedirectFromLoginPage method of forms authentication failed to redirect to originally requested pagememberMatt Sollars18 May '09 - 7:52 
Thank you. I appreciate your efforts. I'll see what I can dig up as well.
 

Matt
www.geekfreeq.com
 
Help my dad get a Wii at MyDadNeedsAWii.com

GeneralSecuring an entire web sitememberMember 40881986 Jun '08 - 2:22 
What if I'm looking to secure the entire site and then just ignore certain directories.
 
Can I add a setting?
 
Thanks
Jerome
GeneralRe: Securing an entire web sitememberMatt Sollars6 Jun '08 - 3:56 
Hi Jerome,
 
That's a great question. I assume by "ignore", you mean allow certain directories to be viewed without encryption (via HTTP). Please, upgrade to the latest version. There is a new article where the latest code is posted here:
http://www.codeproject.com/aspnet/WebPageSecurity_v2.asp[^]
 
You'll notice there are a lot of new features in the latest versions. You can easily accomplish your desired functionality with a configuration similar to the following.
 
For .NET 1.1
<secureWebPages ...>
    <file path="BasicPage.aspx" secure="Insecure" />    
    <directory path="SomeLessImportantDirectory" secure="Insecure" />
    <directory path="Another/SubDirectory" recurse="true" secure="Insecure" />
    <directory path="/" recurse="true" />
</secureWebPages>
 
For .NET 2.0+
<secureWebPages ...>
    <files>
        <add path="BasicPage.aspx" secure="Insecure" />
    </files>
    <directories>
        <add path="SomeLessImportantDirectory" secure="Insecure" />
        <add path="Another/SubDirectory" recurse="true" secure="Insecure" />
        <add path="/" recurse="true" />
    </directories>
</secureWebPages>
 
Please note: The module processes files before directories for a match to the current request. Also, when processing the entries (files and directories), they are evaluated in order and the first match prevails. So, keep in mind that order matters; that's why I have the directory entry for the root of the site last. Otherwise, the recurse attribute set to true for the root would cause any directory being evaluated to generate a match; thus, stopping the process and securing the request.
 
To reiterate, make sure your broadest matching rules are last.
 

Matt

(Find your own niche! This one's mine.)

QuestionRe: Securing an entire web sitememberdeb14324712 Sep '09 - 19:21 
hello matt, i download a demo version hoping to get a full understanding of the project but i keeping getting an error message each time i tried to run it. the error message is
 
Parser Error Message: Could not load file or assembly 'WebPageSecurity' or one of its dependencies.
 
Line 24: <system.web>
Line 25: <httpModules>
Line 26: <add name="SecureWebPages" type="Hyper.Web.Security.SecureWebPageModule, WebPageSecurity" />
Line 27: <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
Line 28: </httpModules>
 
pls what should i do from here and is it possible a get a sample code on VB.
 
Thanks
AnswerRe: Securing an entire web sitememberMatt Sollars13 Sep '09 - 10:18 
First, I recommend you get the latest version from my other article. I'm trying to see if I can have this old article removed.
Switching Between HTTP and HTTPS Automatically: Version 2[^]
 
That new article and code has VB samples and a new demo. Make sure the assembly is copied to the bin folder of the demo (just in case it is not already).
 

Matt
www.geekfreeq.com
 
Help my dad get a Wii at MyDadNeedsAWii.com

GeneralRe: Securing an entire web sitememberdeb14324713 Sep '09 - 22:19 
Thanks Matt...i tried to test run the new demo but still receives 2 error messages for Ventaur namespace. i copied the ventaur.webpagesecurity.v3x.xsd into my app_code and 1 of the error was rectified. i can i resolve the error for Ventaur.Web.Security.Configuration; namespace. Thank you for your time
GeneralRe: Securing an entire web sitememberMatt Sollars14 Sep '09 - 5:26 
Be sure to copy the WebPageSecurity.dll assembly into the test site's bin directory.
 

Matt
www.geekfreeq.com
 
Help my dad get a Wii at MyDadNeedsAWii.com

GeneralRe: Securing an entire web sitememberdeb14324714 Sep '09 - 13:08 
you are a life saver.
 
thanks a bunch
GeneralRe: Securing an entire web sitememberMatt Sollars15 Sep '09 - 2:58 
You're welcome!
 

Matt
www.geekfreeq.com
 
Help my dad get a Wii at MyDadNeedsAWii.com

GeneralRe: Securing an entire web sitememberdeb14324715 Sep '09 - 22:19 
please is there a way to make the https://..... appears in the window link and also add the secure icon (padlock).
thanks
GeneralRe: Securing an entire web sitememberMatt Sollars16 Sep '09 - 2:54 
That demo is meant for people that do not have a self-signed certificate installed. In those cases, they cannot see a true demonstration. If you have one installed, you will need to change mode="RemoteOnly" to mode="On" in the web.config file for the secureWebPages section. Also, you should comment the entire StyleSheetTheme property out in the BasePage.cs file under the App_Code directory.
 

Matt
www.geekfreeq.com
 
Help my dad get a Wii at MyDadNeedsAWii.com

Questiongetting module working in GoDaddy's ASP.NET 3.5 medium trust environmentmemberpeteheist5 May '08 - 3:30 
I haven't been able to get this module to work in GoDaddy's medium trust environment, but it does work in my .NET 3.5 dev environment (when using either high or medium trust). Unfortunately there's no access at GoDaddy to System.Diagnostics output or event log, so there's not much I can do to debug it short of recompiling with my own custom logging.
 
The behavior is that it's as if I didn't add the httpModule at all (no redirects are happening), but I did. I also tried recompiling the module so it was signed with the .snk file, but there was no change.
 
Any thoughts?
AnswerRe: getting module working in GoDaddy's ASP.NET 3.5 medium trust environmentmemberMatt Sollars5 May '08 - 6:48 
Hello.
 
First, I would highly recommend that you upgrade your version of this module to the latest. There is a new article[^] associated with the new version also.
 
Second, make sure the section definition is defined such that permission is not required. See below.
<configSections>
	...
	<section 
		name="secureWebPages" 
		type="Hyper.Web.Security.SecureWebPageSectionHandler, 
			WebPageSecurity" 
		allowLocation="false"
		requrePermission="false" />
</configSections>
 
Once you switch to the new version (v3.x), make sure to note the change in the module's namespace; "Hyper.Web.Security" to "Ventaur.Web.Security".
 
Good luck!
 

Matt

(Find your own niche! This one's mine.)

QuestionError in FireFoxmemberbfrench15 Sep '07 - 8:25 
When trying to redirect from a secure page to an unsecured page.....my web server gives "service unavailable" I suspect somehow it is caught in an infinite loop...JavaScript keeps calling for the unsecured page. Anyone else see this? I see the same bug in Netscape.
 
thanks
 
-Brian

AnswerRe: Error in FireFoxmemberbfrench15 Sep '07 - 8:26 
BTW....it works great for IE!!
 

thanks
 
-Brian
GeneralRe: Error in FireFoxmemberMatt Sollars17 Sep '07 - 15:31 
Hi Brian,
 
I've not heard from other with problems in Firefox before. I use it just fine. I suspect there may be a server issue. Even something minor on the server can cause the stricter browsers to fail, but IE to just deal with it.
 
Do you have a proxy setup? Are you running ISA Server by chance (or any other server-side firewall)?
 
Similar things have been reported with certain firewall rules in-place, and yes IE will ignore the problems on some occasions.
 

I hope you get things resolved soon! Let me know your findings.
 

Matt

(Find your own niche! This one's mine.)

GeneralRe: Error in FireFoxmemberbfrench19 Sep '07 - 7:32 
Thanks Matt.....it turns out not to be this software at all....it has been very difficult to debug and I'm still trying to get to the bottom of it.
 

Sorry about the false alarm.
 
Thanks for the quick response
 
-Brian

GeneralRe: Error in FireFoxmemberMatt Sollars19 Sep '07 - 8:29 
Hi Brian,
 
I'm sorry you are struggling with the issue. You're very welcome for the little support I can give in the matter.
 

Good luck!
 

Matt

(Find your own niche! This one's mine.)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 7 Jul 2005
Article Copyright 2003 by Matt Sollars
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid