├── .gitattributes ├── .gitignore ├── NuGet.Config ├── YoloDev.MultiTenant.sln ├── global.json └── src └── YoloDev.MultiTenant ├── INamedTenantLookup.cs ├── ITenantProvider.cs ├── RequireTenantMiddleware.cs ├── SubdomainProvider ├── SubdomainTenantProvider.cs └── SubdomainTenantProviderOptions.cs ├── TenantMiddleware.cs ├── TenantMiddlewareExtensions.cs ├── TenantService.cs ├── TenantServiceExtensions.cs ├── YoloDev.MultiTenant.xproj └── project.json /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | build/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | 28 | # MSTest test Results 29 | [Tt]est[Rr]esult*/ 30 | [Bb]uild[Ll]og.* 31 | 32 | # NUNIT 33 | *.VisualState.xml 34 | TestResult.xml 35 | 36 | # Build Results of an ATL Project 37 | [Dd]ebugPS/ 38 | [Rr]eleasePS/ 39 | dlldata.c 40 | 41 | # DNX 42 | project.lock.json 43 | artifacts/ 44 | 45 | *_i.c 46 | *_p.c 47 | *_i.h 48 | *.ilk 49 | *.meta 50 | *.obj 51 | *.pch 52 | *.pdb 53 | *.pgc 54 | *.pgd 55 | *.rsp 56 | *.sbr 57 | *.tlb 58 | *.tli 59 | *.tlh 60 | *.tmp 61 | *.tmp_proj 62 | *.log 63 | *.vspscc 64 | *.vssscc 65 | .builds 66 | *.pidb 67 | *.svclog 68 | *.scc 69 | 70 | # Chutzpah Test files 71 | _Chutzpah* 72 | 73 | # Visual C++ cache files 74 | ipch/ 75 | *.aps 76 | *.ncb 77 | *.opensdf 78 | *.sdf 79 | *.cachefile 80 | 81 | # Visual Studio profiler 82 | *.psess 83 | *.vsp 84 | *.vspx 85 | 86 | # TFS 2012 Local Workspace 87 | $tf/ 88 | 89 | # Guidance Automation Toolkit 90 | *.gpState 91 | 92 | # ReSharper is a .NET coding add-in 93 | _ReSharper*/ 94 | *.[Rr]e[Ss]harper 95 | *.DotSettings.user 96 | 97 | # JustCode is a .NET coding add-in 98 | .JustCode 99 | 100 | # TeamCity is a build add-in 101 | _TeamCity* 102 | 103 | # DotCover is a Code Coverage Tool 104 | *.dotCover 105 | 106 | # NCrunch 107 | _NCrunch_* 108 | .*crunch*.local.xml 109 | 110 | # MightyMoose 111 | *.mm.* 112 | AutoTest.Net/ 113 | 114 | # Web workbench (sass) 115 | .sass-cache/ 116 | 117 | # Installshield output folder 118 | [Ee]xpress/ 119 | 120 | # DocProject is a documentation generator add-in 121 | DocProject/buildhelp/ 122 | DocProject/Help/*.HxT 123 | DocProject/Help/*.HxC 124 | DocProject/Help/*.hhc 125 | DocProject/Help/*.hhk 126 | DocProject/Help/*.hhp 127 | DocProject/Help/Html2 128 | DocProject/Help/html 129 | 130 | # Click-Once directory 131 | publish/ 132 | 133 | # Publish Web Output 134 | *.[Pp]ublish.xml 135 | *.azurePubxml 136 | ## TODO: Comment the next line if you want to checkin your 137 | ## web deploy settings but do note that will include unencrypted 138 | ## passwords 139 | #*.pubxml 140 | 141 | *.publishproj 142 | 143 | # NuGet Packages 144 | *.nupkg 145 | # The packages folder can be ignored because of Package Restore 146 | **/packages/* 147 | # except build/, which is used as an MSBuild target. 148 | !**/packages/build/ 149 | # Uncomment if necessary however generally it will be regenerated when needed 150 | #!**/packages/repositories.config 151 | 152 | # Windows Azure Build Output 153 | csx/ 154 | *.build.csdef 155 | 156 | # Windows Store app package directory 157 | AppPackages/ 158 | 159 | # Visual Studio cache files 160 | # files ending in .cache can be ignored 161 | *.[Cc]ache 162 | # but keep track of directories ending in .cache 163 | !*.[Cc]ache/ 164 | 165 | # Others 166 | ClientBin/ 167 | [Ss]tyle[Cc]op.* 168 | ~$* 169 | *~ 170 | *.dbmdl 171 | *.dbproj.schemaview 172 | *.pfx 173 | *.publishsettings 174 | node_modules/ 175 | orleans.codegen.cs 176 | 177 | # RIA/Silverlight projects 178 | Generated_Code/ 179 | 180 | # Backup & report files from converting an old project file 181 | # to a newer Visual Studio version. Backup files are not needed, 182 | # because we have git ;-) 183 | _UpgradeReport_Files/ 184 | Backup*/ 185 | UpgradeLog*.XML 186 | UpgradeLog*.htm 187 | 188 | # SQL Server files 189 | *.mdf 190 | *.ldf 191 | 192 | # Business Intelligence projects 193 | *.rdl.data 194 | *.bim.layout 195 | *.bim_*.settings 196 | 197 | # Microsoft Fakes 198 | FakesAssemblies/ 199 | 200 | # Node.js Tools for Visual Studio 201 | .ntvs_analysis.dat 202 | 203 | # Visual Studio 6 build log 204 | *.plg 205 | 206 | # Visual Studio 6 workspace options file 207 | *.opt 208 | 209 | # LightSwitch generated files 210 | GeneratedArtifacts/ 211 | _Pvt_Extensions/ 212 | ModelManifest.xml 213 | -------------------------------------------------------------------------------- /NuGet.Config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /YoloDev.MultiTenant.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.23107.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{419D544B-6A7E-4722-AD20-59B4CC00E997}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D281F559-70E7-4F58-92DE-A044150EAECC}" 9 | ProjectSection(SolutionItems) = preProject 10 | global.json = global.json 11 | NuGet.Config = NuGet.Config 12 | EndProjectSection 13 | EndProject 14 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "YoloDev.MultiTenant", "src\YoloDev.MultiTenant\YoloDev.MultiTenant.xproj", "{884767EE-BAF7-476E-A2CA-BCBF7044A1AC}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {884767EE-BAF7-476E-A2CA-BCBF7044A1AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {884767EE-BAF7-476E-A2CA-BCBF7044A1AC}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {884767EE-BAF7-476E-A2CA-BCBF7044A1AC}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {884767EE-BAF7-476E-A2CA-BCBF7044A1AC}.Release|Any CPU.Build.0 = Release|Any CPU 26 | EndGlobalSection 27 | GlobalSection(SolutionProperties) = preSolution 28 | HideSolutionNode = FALSE 29 | EndGlobalSection 30 | GlobalSection(NestedProjects) = preSolution 31 | {884767EE-BAF7-476E-A2CA-BCBF7044A1AC} = {419D544B-6A7E-4722-AD20-59B4CC00E997} 32 | EndGlobalSection 33 | EndGlobal 34 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "projects": [ "src" ] 3 | } 4 | -------------------------------------------------------------------------------- /src/YoloDev.MultiTenant/INamedTenantLookup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace YoloDev.MultiTenant 7 | { 8 | public interface INamedTenantLookup 9 | { 10 | Task Lookup(string name); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/YoloDev.MultiTenant/ITenantProvider.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNet.Http; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace YoloDev.MultiTenant 8 | { 9 | public interface ITenantProvider 10 | { 11 | Task> TryGetTenant(HttpContext context); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/YoloDev.MultiTenant/RequireTenantMiddleware.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNet.Builder; 2 | using Microsoft.AspNet.Http; 3 | using System.Threading.Tasks; 4 | 5 | namespace YoloDev.MultiTenant 6 | { 7 | public class RequireTenantMiddleware 8 | { 9 | static readonly Task CompletedTask = Task.FromResult((object)null); 10 | 11 | readonly RequestDelegate _next; 12 | 13 | public RequireTenantMiddleware(RequestDelegate next) 14 | { 15 | _next = next; 16 | } 17 | 18 | public Task Invoke(HttpContext context, ITenantService service) 19 | { 20 | if (service.Tenant == null) 21 | { 22 | context.Response.StatusCode = 404; 23 | return CompletedTask; 24 | } 25 | 26 | return _next(context); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/YoloDev.MultiTenant/SubdomainProvider/SubdomainTenantProvider.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Framework.OptionsModel; 2 | using System; 3 | using System.Threading.Tasks; 4 | using Microsoft.AspNet.Http; 5 | using Microsoft.Framework.Primitives; 6 | using System.Text.RegularExpressions; 7 | using Microsoft.Framework.DependencyInjection; 8 | using Microsoft.Framework.Logging; 9 | 10 | namespace YoloDev.MultiTenant.SubdomainProvider 11 | { 12 | public class SubdomainTenantProvider : ITenantProvider 13 | where TTenant : class 14 | { 15 | readonly static Tuple Failure = Tuple.Create(default(TTenant), false); 16 | readonly static Regex PortNumberRegex = new Regex(":\\d{1,5}$", RegexOptions.Compiled | RegexOptions.CultureInvariant); 17 | 18 | readonly SubdomainTenantProviderOptions _options; 19 | readonly ILogger _logger; 20 | 21 | public SubdomainTenantProvider(IOptions options, ILoggerFactory factory) 22 | { 23 | _options = options.Value; 24 | _logger = factory.CreateLogger>(); 25 | } 26 | 27 | public async Task> TryGetTenant(HttpContext context) 28 | { 29 | StringValues hostNameHeader; 30 | if (!context.Request.Headers.TryGetValue("Host", out hostNameHeader)) 31 | return Failure; 32 | 33 | if (hostNameHeader.Count != 1) 34 | return Failure; 35 | 36 | var hostName = hostNameHeader[0]; 37 | if (string.IsNullOrEmpty(hostName)) 38 | return Failure; 39 | 40 | // Remove port number 41 | hostName = PortNumberRegex.Replace(hostName, ""); 42 | 43 | string subDomain; 44 | if (!string.IsNullOrEmpty(_options.BaseDomain)) 45 | { 46 | if (!hostName.EndsWith("." + _options.BaseDomain)) 47 | return Failure; 48 | 49 | subDomain = hostName.Substring(0, hostName.Length - _options.BaseDomain.Length - 1); 50 | } 51 | else 52 | { 53 | // Assuming the normal subdomain.dommain.topdomain layout. 54 | // Also, default exception for "localhost". Anything else 55 | // will fail and need to be configured using BaseDomain 56 | // on the options object. 57 | var parts = hostName.Split('.'); 58 | 59 | if (parts[parts.Length - 1] == "localhost") 60 | { 61 | if (parts.Length <= 1) 62 | return Failure; 63 | 64 | subDomain = string.Join(".", new ArraySegment(parts, 0, parts.Length - 1)); 65 | } 66 | else 67 | { 68 | if (parts.Length <= 2) 69 | return Failure; 70 | 71 | subDomain = string.Join(".", new ArraySegment(parts, 0, parts.Length - 2)); 72 | } 73 | } 74 | 75 | if (subDomain.Contains(".") && !_options.AllowMultipleLevels) 76 | return Failure; 77 | 78 | _logger.LogDebug("Subdomain is {0}. Looking up tenant.", subDomain); 79 | var lookup = context.RequestServices.GetRequiredService>(); 80 | 81 | var tenant = await lookup.Lookup(subDomain); 82 | if (tenant == null) 83 | { 84 | if (_options.RequireValidTenant) 85 | { 86 | _logger.LogCritical("Valid tenant for subdomain {0} not found.", subDomain); 87 | context.Response.StatusCode = 404; 88 | return null; 89 | } 90 | else 91 | { 92 | return Failure; 93 | } 94 | } 95 | 96 | return Tuple.Create(tenant, true); 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/YoloDev.MultiTenant/SubdomainProvider/SubdomainTenantProviderOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace YoloDev.MultiTenant.SubdomainProvider 7 | { 8 | public class SubdomainTenantProviderOptions 9 | { 10 | public string BaseDomain { get; set; } = null; 11 | 12 | public bool AllowMultipleLevels { get; set; } = false; 13 | 14 | public bool RequireValidTenant { get; set; } = true; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/YoloDev.MultiTenant/TenantMiddleware.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNet.Builder; 2 | using Microsoft.AspNet.Http; 3 | using System.Threading.Tasks; 4 | 5 | namespace YoloDev.MultiTenant 6 | { 7 | class TenantMiddleware 8 | { 9 | readonly RequestDelegate _next; 10 | 11 | public TenantMiddleware(RequestDelegate next) 12 | { 13 | _next = next; 14 | } 15 | 16 | public async Task Invoke(HttpContext context, TenantService service) 17 | { 18 | if (!await service.SetTenant(context)) 19 | return; 20 | 21 | await _next(context); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/YoloDev.MultiTenant/TenantMiddlewareExtensions.cs: -------------------------------------------------------------------------------- 1 | using YoloDev.MultiTenant; 2 | 3 | namespace Microsoft.AspNet.Builder 4 | { 5 | public static class TenantMiddlewareExtensions 6 | { 7 | public static IApplicationBuilder UseMultiTenant(this IApplicationBuilder app) 8 | { 9 | return app.UseMiddleware(); 10 | } 11 | 12 | public static IApplicationBuilder UseRequireTenant(this IApplicationBuilder app) 13 | { 14 | return app.UseMiddleware(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/YoloDev.MultiTenant/TenantService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNet.Http; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace YoloDev.MultiTenant 8 | { 9 | public interface ITenantService 10 | { 11 | object Tenant { get; } 12 | } 13 | 14 | public interface ITenantService : ITenantService 15 | { 16 | new TTenant Tenant { get; } 17 | } 18 | 19 | abstract class TenantService 20 | { 21 | internal abstract Task SetTenant(HttpContext context); 22 | } 23 | 24 | class TenantService : TenantService, ITenantService 25 | { 26 | readonly ITenantProvider[] _providers; 27 | 28 | public TTenant Tenant { get; private set; } 29 | 30 | object ITenantService.Tenant => Tenant; 31 | 32 | public TenantService(IEnumerable> providers) 33 | { 34 | if (providers == null) 35 | throw new ArgumentNullException(nameof(providers)); 36 | 37 | _providers = providers.ToArray(); 38 | 39 | if (_providers.Length == 0) 40 | { 41 | throw new InvalidOperationException("No tenant providers added"); 42 | } 43 | } 44 | 45 | internal override async Task SetTenant(HttpContext context) 46 | { 47 | foreach(var provider in _providers) 48 | { 49 | var result = await provider.TryGetTenant(context); 50 | if (result == null) // used as a signal from a provider to stop processing. This is basically an error, and request processing should stop 51 | return false; 52 | 53 | if (result.Item2) 54 | { 55 | Tenant = result.Item1; 56 | } 57 | } 58 | 59 | return true; 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/YoloDev.MultiTenant/TenantServiceExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Framework.DependencyInjection; 2 | using YoloDev.MultiTenant; 3 | using YoloDev.MultiTenant.SubdomainProvider; 4 | using System; 5 | 6 | namespace Microsoft.Framework.DependencyInjection 7 | { 8 | public static class TenantServiceExtensions 9 | { 10 | public static ServiceWrapper AddMultiTenant(this IServiceCollection collection) 11 | where TTenant : class 12 | { 13 | collection.AddScoped, TenantService>() 14 | .AddScoped(services => (ITenantService)services.GetService(typeof(ITenantService))) 15 | .AddScoped(services => (TenantService)services.GetService(typeof(ITenantService))); 16 | 17 | return new ServiceWrapper(collection); 18 | } 19 | 20 | public static ServiceWrapper AddSubdomainProvider(this ServiceWrapper collection, Action configureOptions = null) 21 | where TTenant : class 22 | { 23 | var s = collection.ServiceCollection; 24 | s.AddOptions(); 25 | s.AddSingleton ,SubdomainTenantProvider>(); 26 | 27 | if (configureOptions != null) 28 | s.Configure(configureOptions); 29 | 30 | return collection; 31 | } 32 | } 33 | } 34 | 35 | namespace YoloDev.MultiTenant 36 | { 37 | public struct ServiceWrapper 38 | where TTenant : class 39 | { 40 | public ServiceWrapper(IServiceCollection collection) 41 | { 42 | ServiceCollection = collection; 43 | } 44 | 45 | internal IServiceCollection ServiceCollection { get; } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/YoloDev.MultiTenant/YoloDev.MultiTenant.xproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 14.0 5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 6 | 7 | 8 | 9 | 10 | 884767ee-baf7-476e-a2ca-bcbf7044a1ac 11 | YoloDev.MultiTenant 12 | ..\..\artifacts\obj\$(MSBuildProjectName) 13 | ..\..\artifacts\bin\$(MSBuildProjectName)\ 14 | 15 | 16 | 17 | 2.0 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/YoloDev.MultiTenant/project.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.0-*", 3 | "description": "YoloDev.MultiTenant Class Library", 4 | "authors": [ "Alxandr" ], 5 | "tags": [ "" ], 6 | "projectUrl": "", 7 | "licenseUrl": "", 8 | 9 | "dependencies": { 10 | "Microsoft.AspNet.Http.Abstractions": "1.0.0-*", 11 | "Microsoft.Framework.DependencyInjection.Abstractions": "1.0.0-*", 12 | "Microsoft.Framework.OptionsModel": "1.0.0-*", 13 | "Microsoft.Framework.Logging": "1.0.0-*" 14 | }, 15 | 16 | "frameworks": { 17 | "dnx451": { }, 18 | "dnxcore50": { 19 | "dependencies": { 20 | "Microsoft.CSharp": "4.0.1-*", 21 | "System.Collections": "4.0.11-*", 22 | "System.Linq": "4.0.1-*", 23 | "System.Runtime": "4.0.21-*", 24 | "System.Threading": "4.0.11-*", 25 | "System.Text.RegularExpressions": "4.0.11-*" 26 | } 27 | } 28 | } 29 | } 30 | --------------------------------------------------------------------------------