(616) 371-1037

[email protected]

AspNetCore – multi tenant tips and tricks

May 29, 2018 - John Waters

No 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:

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

Leave a comment

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