From d1e0219a128499e035d1c7acf32a9fd2d3317000 Mon Sep 17 00:00:00 2001 From: Chad Gilbert Date: Wed, 1 Mar 2017 12:40:59 -0500 Subject: [PATCH] Add a way to secure paths by regex --- .../BasicAuthentication.cs | 22 +++++++++++++++++++ Readme.md | 5 +++++ 2 files changed, 27 insertions(+) diff --git a/Hexasoft.BasicAuthentication/Hexasoft.BasicAuthentication/BasicAuthentication.cs b/Hexasoft.BasicAuthentication/Hexasoft.BasicAuthentication/BasicAuthentication.cs index 8e2ffeb..3e0378d 100644 --- a/Hexasoft.BasicAuthentication/Hexasoft.BasicAuthentication/BasicAuthentication.cs +++ b/Hexasoft.BasicAuthentication/Hexasoft.BasicAuthentication/BasicAuthentication.cs @@ -1,15 +1,33 @@ using System; using System.Configuration; using System.Text; +using System.Text.RegularExpressions; using System.Web; namespace Hexasoft { public class BasicAuthentication : IHttpModule { + static Regex requirePathRegex; + public void Init(HttpApplication context) { context.BeginRequest += ContextBeginRequest; + + var regexRaw = ConfigurationManager.AppSettings["BasicAuthentication.RequiredOnPathRegex"]; + var ignoreCaseRaw = ConfigurationManager.AppSettings["BasicAuthentication.RequiredOnPathRegex.IgnoreCase"]; + + if (!string.IsNullOrEmpty(regexRaw)) + { + var options = RegexOptions.None; + + if (string.Equals(ignoreCaseRaw, "true", StringComparison.InvariantCultureIgnoreCase) || ignoreCaseRaw == "1") + { + options |= RegexOptions.IgnoreCase; + } + + requirePathRegex = new Regex(regexRaw, options); + } } private void ContextBeginRequest(object sender, EventArgs e) @@ -38,6 +56,10 @@ private bool Required() requiredSetting = requiredSetting.Trim().ToLower(); required = requiredSetting == "1" || requiredSetting == "true"; } + else if (requirePathRegex != null) + { + required = requirePathRegex.IsMatch(HttpContext.Current.Request.Url.AbsolutePath); + } return required; } diff --git a/Readme.md b/Readme.md index d2c9736..aabd80d 100644 --- a/Readme.md +++ b/Readme.md @@ -23,6 +23,11 @@ After installing the package you will see 3 new settings in the `appSettings` se Use the `BasicAuthentication.Required` to quickly turn the authentication on or off while the username/password settings are self explanatory. Username is case-insensitive, password is case-sensitive. +As an alternative to securing the entire site, you can specify a regular expression to match against the URL Path by replacing the `"BasicAuthentication.Required"` appSetting with something like the following: + + + + As this module was meant to secure WebApi's behind an Azure API Management, it only supports one username/password combination. No support for multiple users,