1

I am trying to validate token in multi tenant application. In startup(single tenant) earlier used this code for getting configuration data from appsettings.json.

 services.AddMicrosoftIdentityWebApiAuthentication(Configuration);

But now we need to load configurations data from database. So i have added below code to startup.

    services.AddAuthentication("Bearer").AddJwtBearer("Bearer",
    options =>
    {
        options.Authority = "http://localhost:3000";
        options.Audience = "fcb78955-1a4a-6666-aa12-fc473b8fd8f6";
        options.RequireHttpsMetadata = false;

        options.TokenValidationParameters = new
          TokenValidationParameters()
        {
            ValidateAudience = false
        };
    });

and this is my token validation code. I have hardcode this for testing purpose. so please ignore it.

 public static async Task<ClaimsPrincipal> TokentValidate(string token, string tenantId, string clientId)
        {
            try
            {
var authorityEndpoint = "https://demo.identityserver.io/";
            authorityEndpoint = "https://login.microsoftonline.com/" + "9111f39b-e5ed-8899-9c13-0005388e683a" + "/";
            var openIdConfigurationEndpoint = $"{authorityEndpoint}.well-known/openid-configuration";
            IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(openIdConfigurationEndpoint, new OpenIdConnectConfigurationRetriever());
            OpenIdConnectConfiguration openIdConfig = await configurationManager.GetConfigurationAsync(CancellationToken.None);
            clientId = "f0019d64-100a-4990-aa12-fc663b8899f6";
            TokenValidationParameters validationParameters = new TokenValidationParameters
            { 
                ValidIssuer = openIdConfig.Issuer,
                ValidAudiences = new[] { clientId },
                IssuerSigningKeys = openIdConfig.SigningKeys,
                ValidateLifetime = true,
                ValidateAudience = false,
                ValidateIssuer = false,
                ValidateIssuerSigningKey = true
            };
            SecurityToken validatedToken;
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            var user = handler.ValidateToken(token, validationParameters, out validatedToken); 
            return user; 
     }
            catch (Exception ex)
            {
                return null;
            }
        }

But this method not calling. So I have removed startup code. then i am getting this error.

{"Error":"No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions)."}

I want to if we are using multi tenant and loading configurations from database what is the correct way. If anyone have an idea please help.

AlexDemo
  • 141
  • 3
  • 14

0 Answers0