FREE WEBINAR: "It's Time to Migrate Your Team to .NET Core" Register Now!

(616) 371-1037

[email protected]

AspNetCore – multi tenant tips and tricks

May 29, 2018 - John Waters

11 Comments

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,
                    @"http://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

11 thoughts on “AspNetCore – multi tenant tips and tricks

  • Zak Abdulai

    July 27, 2018 at 12:46 pm

    Hi John,

    Thanks very much for this amazing article. I’m trying to adapt your code in my project and was wondering if you a small application with the various parts explained in your article.

    Kind Regards,
    Zak

    Reply
    • John Waters

      August 10, 2018 at 3:57 am

      No, the examples are taken from quite a large app.

      Reply
  • Fabri

    August 27, 2018 at 9:48 pm

    Hey John, amazing article! I’m implementing your solution into an application and i hope i have enough skills to do it. I just wanna say tkx for share part of your knowledge with us!

    Reply
  • Glenn Morton

    October 8, 2018 at 7:08 am

    Hey John,

    Good article! How do you deal with change to the list of user roles, do you force the user to log out in order for the new roles to take effect?

    Reply
    • John Waters

      October 8, 2018 at 10:39 am

      Yes, they have to log out and log back in.

      Reply
  • Praveen

    October 8, 2018 at 8:35 am

    John – you are amazing sir. Thanks for the writeup – DEFINITELY picked up a few tricks 🙂

    Reply
  • Srivathsa Harish Venkataramanan

    October 22, 2018 at 9:44 am

    Hi, thanks for the post and it is good, one small thing. You have specified JWT as Java Web Token however I think it is JSON Web Token

    Reply
  • Michael

    November 12, 2018 at 10:07 pm

    Very nice article John! Thank you for taking your time to help other out.

    Reply
  • Paco

    May 28, 2019 at 10:49 pm

    I am applying the example in ASP.NET Core 2.2 with several layers, but when launching the web application I get the following error:

    InvalidOperationException: Unable to resolve service for type ‘{PROJECT} .Domain.Entities.Common.IUserSession’ while attempting to Invoke middleware ‘{PROJECT} .WebApi.Middlewares.ConfigureSessionMiddleware’.

    Reply
    • John Waters

      June 4, 2019 at 4:44 pm

      Check your DI setup and make sure you are registering IUserSession as a Scoped Dependency, in my code I have: services.AddScoped<IUserSession, Session>();

      Reply
  • Keith Fimreite

    August 22, 2019 at 2:59 am

    Hi John I have attempted to implement your user session and the IAuditable in my repo: https://github.com/enkodellc/blazorboilerplate I could not get the IUserSession to populate at all. I am using .net Core 3 so maybe there is some changes. Maybe you could take a look and then use my repo as a resource for others to see the full implementation. Thanks for the blogs!

    Reply

Leave a comment to Glenn Morton Cancel reply

Your email address will not be published. Required fields are marked *