(616) 371-1037

[email protected]

AspNetCore – multi tenant tips and tricks

May 29, 2018 - John Waters


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:

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

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

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:


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.

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.

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:

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:

I then implement it as follows:

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

As you recall, this happens in my Startup code:

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:

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

The middleware is pretty simple:

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:

And my ApiController base class:

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

10 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,

    • John Waters

      August 10, 2018 at 3:57 am

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

  • 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!

  • 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?

    • John Waters

      October 8, 2018 at 10:39 am

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

  • Praveen

    October 8, 2018 at 8:35 am

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

  • 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

  • Michael

    November 12, 2018 at 10:07 pm

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

  • 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’.

    • 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>();


Leave a comment

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