title: How to achieve multi-tenant authentication with firebase in a .net core web api
body: <p>I'm plannig to build an SaaS application using .net core web api and for authentication I want to use firebase. In summary, what I am trying to achieve is to have one database per Tenant for safety reasons and ease of implementation. Each tenant will have his own subdomain. In this application, one user can be registered to multiple tenants, so when an user logs in, he is prompted to select which tenant he wants to access and once chooses it, he is then redirected to the appropriate tenant.</p>
  <p>All the transactions performed by an user in a specific tenant will be recorded in a relational database that will be managed by a .net core web api + EF core application. I intend to use cloud firestore only for management of tentant specific configuration and users.</p>
  <p>So far, I have one firebase project that I intend to use to manage tenants and users and authenticate/authorize these users based on their roles that will be stored in custom claims issued by firebase.</p>
  <p>So, basically: user enters his e-mail in to <a href="http://www.myapp.com" rel="nofollow noreferrer">www.myapp.com</a> -&gt; select a tenant (if multiple) -&gt; user types password for the specific tenant -&gt; if authenticated redirects to <a href="http://www.tenant1.myapp.com" rel="nofollow noreferrer">www.tenant1.myapp.com</a>.</p>
  <p>Once he is in <a href="http://www.tenant1.myapp.com" rel="nofollow noreferrer">www.tenant1.myapp.com</a>, all the operations performed by that user are authorized based on the claims that have been set to his token and recorded in tenant's specific database.</p>
  <p>This is the client side code to create an user:</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>    var cadastroForm = document.getElementById('cadastroForm')
      cadastroForm.onsubmit = function (event) {
        event.preventDefault()
  
        console.log('Locatario em que será feito o cadastro: ', locatarioSelecionado.value)
    
        firebase.auth().tenantId = locatarioSelecionado.value
        firebase.auth().createUserWithEmailAndPassword(newUsername.value, 
  newPassword.value).then(function (result) {
          console.log('Novo usuário criado no locatário ' + locatarioSelecionado.value)
          //console.log(result)
        }).catch(function (error) {
          console.log('Erro ao criar usuário no locatário ' + locatarioSelecionado.value)
        })
  
        firebase.auth().onAuthStateChanged(function (user) {
          console.log(user)
        })
  
      }</code></pre>
  </div>
  </div>
  </p>
  <p>This is the code used to authenticate user:</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var locatarioSelecionado = document.getElementById('locatarioSelecionado') // TENANT ID.
      loginForm.onsubmit = function (event) {
        event.preventDefault()
        console.log(locatarioSelecionado.value)
  
        firebase.auth().tenantId = locatarioSelecionado.value
        firebase.auth().signInWithEmailAndPassword(username.value, password.value).then(function 
  () {
          console.log('Login bem sucedido.')
    
        })
        .catch(function (error) {
          console.log('Falha no acesso: ')
          console.log(error)
        })
  
        firebase.auth().onAuthStateChanged(function (user) {
          console.log(user)
        })
      }</code></pre>
  </div>
  </div>
  </p>
  <p>Using this code, let's say I create user1@gmail.com and select cliente001 (the tenant, in this case). However, even though I selected client001 for that user, when I try to log in using cliente002, I still get this when I do console.log(user) : tenantId: &quot;cliente001-od9s9&quot;.</p>
  <p>I did no expect user1@gmail.com to be able to authenticate to cliente002 since he is only registered to cliente002, but he is authenticated.</p>
  <p><strong>.net core api: database selection</strong></p>
  <p>Now let's say I complete the first step and the user is authenticated by google in tenant1 successfully, how can I redirect incoming requests to a specific database in an .net core web api using EF core based on the validated JWT token?</p>
  <p>So far, I have managed to authenticate a user using JWT token using this code in Startup.cs:</p>
  <pre><code>public void ConfigureServices(IServiceCollection services)
      {
          services.AddControllers();
          services.AddSwaggerGen(c =&gt;
          {
              c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo 
                { 
                  Title = &quot;AspNetCoreWebApiGoogleIdentityAuth&quot;, 
                  Version = &quot;v1&quot; 
                });
          });
          services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =&gt; 
            {
              options.Authority = &quot;https://securetoken.google.com/sgpa-auth-prototype&quot;;
              options.TokenValidationParameters = new TokenValidationParameters
              {
                ValidateIssuer = true,
                ValidIssuer = &quot;https://securetoken.google.com/sgpa-auth-prototype&quot;,
                ValidateAudience = true,
                ValidAudience = &quot;sgpa-auth-prototype&quot;,
                ValidateLifetime = true
              };
            });
      }
  </code></pre>
  <p>But from this I still have no idea on how to redirect requests to a specific tenant's datase and subdomain.</p>