title: ASP.NET Core with IdentityServer4 - multiple tenants - changing authority at runtime
body: <p>We have a SaaS platform in which we are on a process to migrate it to a Multi-Tenants architecture. We have multiple micro-services and one Identity server which uses IdentityServer4.</p>
  
  <p>In each service in the <code>Startup.cs</code> we have the following code:</p>
  
  <pre><code>services.AddAuthentication("Bearer")
          .AddIdentityServerAuthentication(options =&gt;
          {
              options.Authority = Configuration["URLs:IdentityServer"];
              options.RequireHttpsMetadata = false;
  
              options.ApiName = "apiInternal";
          });
  </code></pre>
  
  <p>We are using subdomains to distinguish between tenants and each tenant has its own database.</p>
  
  <p>The only problem we are facing is with the IdentityServer.</p>
  
  <p>Our goal is that we will have a different Identity service for each tenant. But we could not figure out how to replace the authority at runtime based on the subdomain (tenant).</p>
  
  <p>Actually, we tried this approach:</p>
  
  <p><a href="https://stackoverflow.com/questions/52955238/how-can-i-set-the-authority-on-openidconnect-middleware-options-dynamically">How can I set the Authority on OpenIdConnect middleware options dynamically?</a></p>
  
  <p>After some changes it worked with only one problem, the authority is changing only on the first request, meaning, if the first request was from tenant1.example.com it will use the tenant1 identity authority, but any other request will "change" the authority but will use tenant1 authority. </p>
  
  <p>For example, if the second request is from tenat2.example.com we will see the code that changes the authority kick in, but in actual, it is not replacing the authority. </p>
  
  <p>What I suspect that happens is that the authority has changed, but it does not initialize the IdentityServer data.</p>
  
  <p>If that is actually the problem, I have a couple of questions:</p>
  
  <p>How do I solve it?</p>
  
  <p>What do you think the performance impact will be given the fact that on each request, we will have to get the IdentityServer data for token validation?</p>
  
  <p>Any other ideas what would be a best practice for having idenityserver4 with a multi-tenants approach?</p>