AspNetCore – multi tenant tips and tricks

In two recent posts, I blogged about SignalR in .AspNet Core 2.1, and automating boilerplate multitenancy code in Entity Framework Core 2.1.
Both these blogs alluded to knowing the identity of the calling user through claims and dependency injection. This blogs ties together those loose ends to show how that can be done.

Authenticating the User

The first part to the puzzle is authenticating the user, i.e. the caller of the Web API or SignalR Hub. There are many ways to do this. I like to use JWTs (Java Web Tokens), which encode a series of claims about a user (i.e. their user id, tenant id, roles…) in a tamper proof token. This token can be supplied in the HTTP Authorization header, or on a query string. To use the built in AspNetCore Jwt Bearer Token support, you’ll want to add AddAuthentication and AddJwtBearer to your services collection:

        public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddOptions()
                .AddConfig(ConfigurationRoot)
                .AddCORS()
                .AddEF(ConfigurationRoot)
                .ConfigureApplicationInjection()
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    var tokenOptions = ConfigurationRoot.GetSection("Authentication").Get<TokenOptions>();
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = tokenOptions.Issuer,
                        ValidAudience = tokenOptions.Audience,
                        IssuerSigningKey = new SymmetricSecurityKey(
                            Encoding.UTF8.GetBytes(tokenOptions.SigningKey))
                    };
                });
            services.AddMvc();
            services.AddSignalR();
            services.AddSwagger();
            services.AddAutoMapper();
        }

The bearer token needs some configuration, including the issuer, audience and signing key. I store these in my appsettings.json file:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "local": "xxx",
    "AzureWebJobsDashboard": "xxx",
    "AzureWebJobsStorage": "xxx"
  },
  "Authentication": {
    "SigningKey": "xxxx",
    "Issuer": "northstarapi",
    "Audience": "northstar",
    "ExpirationMinutes": 180
  },
  "Azure": {
    "SignalR": {
      "ConnectionString": "xxx"
    }
  }
}

Next, in your Configure method, use these services to place them in the HTTP pipeline (UseAuthentication) :

        public void Configure(IApplicationBuilder app)
        {
            app
                .UseTokenInQueryString()
                .UseAuthentication()
                .UseConfigureSession()
                .UseSwagger(
                    c =>
                    {
                        c.PreSerializeFilters.Add(
                            (swagger, httpReq) => swagger.Host = httpReq.Host.Value);
                    })
                .UseSwaggerUI(c =>
                {
                    // when running in a Docker container this is null and needs adjusting
                    var basePath = Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH") ?? "/";
                    c.SwaggerEndpoint(basePath + "swagger/v1/swagger.json", "V1 Docs");
                    c.DocExpansion(DocExpansion.None);
                })
                .UseDeveloperExceptionPage()
                .UseHttpException()
                .UseCors("AllowAllCorsPolicy")
                .UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                })
                .UseSignalR(
                    routes => { routes.MapHub<StopsHub>("/stophub"); });
            var config = new MapperConfiguration(cfg => {
                cfg.AddProfile<MappingProfile>();
            });
        }

This is enough to cause AspNetCore to automatically take any JWT in an HTTP Authorization Bearer XXX header and validate it, putting any claims found in the token into the ClaimsPrincipal that is in your ApiController or Hub User objects.
One trick here is the call to UseTokenInQueryString. The build in token validation expects the token to be in the HTTP header, but in some cases, it is in a query string. For instance, if you have an API that returns a document via a GET operation bound to an image tag, you can’t set any HTTP headers. Or, when negotiating the initial SignalR handshake, the token is sent on the query string too. UseTokenInQueryString adds a custom middleware that does this job:

    public static class ApplicationBuilderExtensions
    {
        public static IApplicationBuilder UseTokenInQueryString(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<GetTokenFromQueryStringMiddleware>();
        }
    }

And

    public class GetTokenFromQueryStringMiddleware
    {
        private readonly RequestDelegate _next;
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="next">the next middleware in chain</param>
        public GetTokenFromQueryStringMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            if (string.IsNullOrWhiteSpace(context.Request.Headers["Authorization"]))
            {
                if (context.Request.QueryString.HasValue)
                {
                    var token = context.Request.QueryString.Value.Split('&')
                        .SingleOrDefault(x => x.Contains("token"))?.Split('=')[1];
                    if (!string.IsNullOrWhiteSpace(token))
                    {
                        context.Request.Headers.Add("Authorization", new[] { $"Bearer {token}" });
                    }
                }
            }
            await _next.Invoke(context);
        }
    }

Now if any query string variable containing “token” is found, it’s value is added as the HTTP Authorization header.
Now we have code in place that can recognize and validate any incoming JWTs, but how do we create them and add the claims? In my case, I do this using an ApiController that exposes a Token endpoint, which of course is marked with [AllowAnonymous] since the user is not logged in when they call it. The method receives the user’s login credentials, in this case through a TokenRequestDTO (passed as JSON in the Request Body). You could also follow the standard method of putting them in an Authorize Basic BASE64Username:Password header.

        public TokenController
        (
            IUserSession currentSession,
            IMapper mapper,
            IHubHelper hubHelper,
            IUserRepo userRepo,
            ITenantRepo tenantRepo,
            IOptions<TokenOptions> tokenOptions) : base(currentSession, hubHelper, mapper)
        {
            _tokenOptions = tokenOptions.Value;
            _userRepo = userRepo;
            _tenantRepo = tenantRepo;
        }
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Token([FromBody]TokenRequestDTO req)
        {
            // we won't know which tenant the user belongs to until found
            CurrentSession.DisableTenantFilter = true;
            var user = await _userRepo.GetByEmailAsync(req.Username);
            if (user == null)
            {
                return ValidationError("Invalid username/password combination.");
            }
            if (CryptoHelper.IsValid(req.Password, user.PasswordSalt, user.PasswordHash))
            {
                var entry = _userRepo.Context.Entry(user);
                var tenantId = entry.Property<int>("TenantId").CurrentValue;
                // now we can set the tenant and user for this session
                CurrentSession.DisableTenantFilter = false;
                CurrentSession.TenantId = tenantId;
                CurrentSession.UserId = user.Id;
                var tenant = await _tenantRepo.GetAsync(tenantId, new[] { "Logo", "Subscription" });
                return Ok(TokenHelper.CreateToken(
                    user,
                    tenant,
                    _tokenOptions,
                    Mapper.Map<DocumentDTO>(tenant.Logo)));
            }
            return ValidationError("Invalid username/password combination.");
        }

Once you have the username and password, you validate against your credential store. I do this by searching for a matching user name (actually a matching email). Note the code that sets DisableTenantFilter=true. If you read my other post on EF Core, you will see that is because I can’t filter the User table by TenantId yet, because I don’t know the Tenant until the user has logged in!
If I find a matching User, I then check the username and password. My CryptoHelper hashes the password, adds it to the stored Salt in the User object, and then compares to the stored Salted Hash.

    public static class CryptoHelper
    {
        public static byte[] GenerateSalt()
        {
            // Define min and max salt sizes.
            var minSaltSize = 4;
            var maxSaltSize = 8;
            // Generate a random number for the size of the salt.
            var random = new Random();
            var saltSize = random.Next(minSaltSize, maxSaltSize);
            // Allocate a byte array, which will hold the salt.
            var saltBytes = new byte[saltSize];
            // Initialize a random number generator.
            var rng = RandomNumberGenerator.Create();
            // Fill the salt with cryptographically strong byte values.
            //rng.GetNonZeroBytes(saltBytes);
            rng.GetBytes(saltBytes);
            return saltBytes;
        }
        /// <summary>
        /// Check if the supplied password is valid
        /// </summary>
        /// <param name="password">The password sent by the user</param>
        /// <param name="passwordSalt">The stored password salt</param>
        /// <param name="hashedPassword">The stored hashed password</param>
        /// <returns></returns>
        public static bool IsValid(string password, byte[] passwordSalt, byte[] hashedPassword)
        {
            using (var hash = SHA512.Create())
            {
                var saltedPlainTextBytes = Encoding.UTF8.GetBytes(password).Concat(passwordSalt).ToArray();
                var hashedBytes = hash.ComputeHash(saltedPlainTextBytes);
                return hashedBytes.SequenceEqual(hashedPassword);
            }
        }
        public static byte[] HashPassword(string value, byte[] passwordSalt)
        {
            using (var hash = SHA512.Create())
            {
                var saltedPlainTextBytes = Encoding.UTF8.GetBytes(value).Concat(passwordSalt).ToArray();
                var hashedBytes = hash.ComputeHash(saltedPlainTextBytes);
                return hashedBytes;
            }
        }
    }
}

Once validated, I get the TenantId from the UserObject, set the UserSession TenantId and UserId., and fetch the Tenant object. More on that UserSession later. Finally, my Token helper creates the JWT:

    public static class TokenHelper
    {
        public static TokenResponseDTO CreateToken(User user, Tenant tenant, TokenOptions options,
            DocumentDTO tenantLogo)
        {
            var claims = new List<Claim> {
                new Claim("userid", user.Id.ToString(), ClaimValueTypes.Integer),
                new Claim("username", user.Email, ClaimValueTypes.String),
                new Claim("tenantid", tenant.Id.ToString(), ClaimValueTypes.Integer)
            };
            var roleNames = user.Roles.Select(ur => ur.Role.Name).Distinct().ToList();
            if (roleNames.Any())
            {
                claims.AddRange(
                    roleNames.Select( rn => new Claim("role", rn, ClaimValueTypes.String)));
            }
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.SigningKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.UtcNow.AddMinutes(options.ExpirationMinutes);
            var token = new JwtSecurityToken(options.Issuer, options.Audience, claims, expires: expires, signingCredentials: creds);
            return new TokenResponseDTO
            {
                Token = new JwtSecurityTokenHandler().WriteToken(token),
                Expires = expires,
                Username = user.Email,
                UserFirstName = user.FirstName,
                UserLastName = user.LastName,
                TenantName = tenant.Name,
                TenantLogo = tenantLogo,
                Roles = user.Roles.Select( ur => new RoleDTO
                {
                    Id = ur.RoleId,
                    Name = ur.Role.Name
                }).ToList()
            };
        }
    }

Here are some key points about the token creation:

  • First, I add the tenantid, userid and username claims to the list of claims
  • Then, I add role claims (there can be multiple). I have a user.Roles table that contains these. This allows me to decorate my ApiControllerMethods with attributes like [Authorize(Roles = “SystemAdmin”)], allowing only callers with a token containing the SystemAdmin role claim to call that method
  • The issuer, audience, expiration and signing key all come from that same appSettings.json section I showed in the Startup configuration. Here, the options are passed into the TokenHelper. They originally where injected into the TokenController constructor
  • For the convenience of the caller (an Angular app), I return the token wrapped in a DTO, that also has the name of the user, tenant, tenant logo and user roles. These are used by the UI to show who is logged in and which tenant:


The caller stores the JWT (taking note of the expiration date), and will supply it in all subsequent calls, either in the HTTP Authorize Bearer JWT header, or on the query string.
The piece that ties this blog together with that on EF Core, and SignalR, is the maintaining of a User Session. The way I do this is to declare an interface:

    public interface IUserSession
    {
        int UserId { get; set; }
        int TenantId { get; set; }
        List<string> Roles { get; set; }
        string UserName { get; set; }
        bool DisableTenantFilter { get; set; }
    }

I then implement it as follows:

    public class Session : IUserSession
    {
        public int UserId { get; set; }
        public int TenantId { get; set; }
        public List<string> Roles { get; set; } = new List<string>();
        public string UserName { get; set; }
        public bool DisableTenantFilter { get; set; }
    }

I register the mapping while configuring dependency injection for the app:

        public static IServiceCollection ConfigureApplicationInjection(this IServiceCollection services)
        {
            services.AddScoped<IUserSession, Session>();

As you recall, this happens in my Startup code:

        public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddOptions()
                .AddConfig(ConfigurationRoot)
                .AddCORS()
                .AddEF(ConfigurationRoot)
                .ConfigureApplicationInjection()
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>

Note the Dependency has the lifetime of Scoped, meaning you get an instance of this for each WebAPI call, or SignalR hub call.
Next, I define another custom middleware that populates this object with data form the claims in the JWT:

       public void Configure(IApplicationBuilder app)
        {
            app
                .UseTokenInQueryString()
                .UseAuthentication()
                .UseConfigureSession()

This is done above by UseConfigureSession, an AppBuilder extension method that installs the middleware:

    public static class ApplicationBuilderExtensions
    {
        public static IApplicationBuilder UseConfigureSession(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<ConfigureSessionMiddleware>();
        }

The middleware is pretty simple:

    public class ConfigureSessionMiddleware
    {
        private readonly RequestDelegate _next;
        public ConfigureSessionMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task InvokeAsync(HttpContext context, IUserSession session)
        {
            if (context.User.Identities.Any(id => id.IsAuthenticated))
            {
                session.UserId = ClaimsHelper.GetClaim<int>(context.User, "userid");
                session.TenantId = ClaimsHelper.GetClaim<int>(context.User, "tenantid");
                session.Roles = ClaimsHelper.GetClaims<string>(context.User,
                    @"https://schemas.microsoft.com/ws/2008/06/identity/claims/role");
                session.UserName = ClaimsHelper.GetClaim<string>(context.User, "username");
            }
            // Call the next delegate/middleware in the pipeline
            await _next.Invoke(context);
        }
    }

Note how I get the correct UserSession injected into the InvokeAsync call, and just set the properties from the values in the ClaimsPrincipal found in context.User. By the time this middleware is called, the Jwt handler has already validated the token and created a ClaimsPrincipal with the claims encoded in the JWT.
Now, the rest of my code, be it in an ApiController, an EntityFramework Global Query, a SignalR HubContext or a Repository class, has access to the current UserId and TenantId – it just has to declare a IUserSession in it’s constructor to have this instance injected.
Here it is in my DbContext class:

    public class AppDbContext : DbContext
    {
        private readonly IUserSession _userSession;
        public AppDbContext(DbContextOptions options, IUserSession userSession)
            : base(options)
        {
            _userSession = userSession;
        }

And my ApiController base class:

    [Authorize]
    public class AuthControllerBase : ControllerBase
    {
        protected IUserSession CurrentSession { get; }
        public AuthControllerBase
        (
            IUserSession currentSession,
            IMapper mapper) : base(mapper)
        {
            CurrentSession = currentSession;
        }

And that’s a wrap! As I mentioned before, at Trailhead we find a lot of these patterns in different systems, so we built the Trailhead Technology Framework to reuse these in our consulting projects. Who know, maybe the next one will be with you!
 
 
 

John Waters

John Waters

As a highly respected and recommended technology leader, entrepreneur, and software architect extraordinaire, John Waters provides guidance for Trailhead teams and projects. His remarkable project requirements gathering and project estimation skills allow him to oversee teams that deliver client projects on time and on budget. John’s background includes over two decades of systems architecting, implementations for a range of high-performance business solutions, and speaking at conferences worldwide.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Manage Your Windows Applications With Winget

Winget, Microsoft’s native package manager for Windows 10 (version 1709 and later) and Windows 11, offers a streamlined CLI for efficient application management. This blog post introduces Winget’s installation and basic commands for installing, updating, and removing software. It highlights the tool’s ability to manage non-Winget-installed apps and explores curated package lists for batch installations. The post also recommends top Winget packages, noting some may require a paid subscription.

Read More

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.