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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With