Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to determine if HTTPS

Tags:

c#

security

https

How do I determine and force users to view my website using HTTPS only? I know it can be done through IIS, but want to know how its done programmatically.

like image 708
jinsungy Avatar asked Jul 13 '09 15:07

jinsungy


1 Answers

You can write an HttpModule like this:

/// <summary>
/// Used to correct non-secure requests to secure ones.
/// If the website backend requires of SSL use, the whole requests 
/// should be secure.
/// </summary>
public class SecurityModule : IHttpModule
{
    public void Dispose() { }

    public void Init(HttpApplication application)
    {
        application.BeginRequest += new EventHandler(application_BeginRequest);
    }

    protected void application_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication application = ((HttpApplication)(sender));
        HttpRequest request = application.Request;
        HttpResponse response = application.Response;

        // if the secure connection is required for backend and the current 
        // request doesn't use SSL, redirecting the request to be secure
        if ({use SSL} && !request.IsSecureConnection)
        {
            string absoluteUri = request.Url.AbsoluteUri;
            response.Redirect(absoluteUri.Replace("http://", "https://"), true);
        }
    }
}

Where {use SSL} is a some condition whether to use SSL or not.

EDIT: and, of course, don't forget to add a module definition to a web.config:

<system.web>
    <httpModules>
        <!--Used to redirect all the unsecure connections to the secure ones if necessary-->
        <add name="Security" type="{YourNamespace}.Handlers.SecurityModule, {YourAssembly}" />
        ...
    </httpModules>
</system.web>
like image 76
Oleks Avatar answered Sep 29 '22 23:09

Oleks