在不重新启动.NET应用程序的情况下使用Keycloak实现.NET 6中的多租户

jecbmhm3  于 2023-03-09  发布在  .NET
关注(0)|答案(1)|浏览(227)

我尝试在.NET 6应用程序中实现多租户以授权后端API。我通过添加多个领域信息成功实现了这一点(发布者和受众)在appSettings.json和jwt架构中,在program.cs文件中。但我的问题是,我希望在.NET应用程序处于运行状态时实现相同的多租户,因为我不想**重启应用程序(生产)**在Keycloak内部创建新领域时。
我尝试通过ServiceCollection将新创建的领域信息注入到JWT Schema中,但无法运行,因为我不允许在应用程序运行时注入新服务。
我也尝试过通过中间件来实现,我能够在运行时添加新的中间件,它具有新创建的领域的模式,但它仍然无法识别模式。
有没有办法在不重建应用程序的情况下添加多租户支持?

b4lqfgs4

b4lqfgs41#

我也尝试了中间件,但没有效果

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NuGet.Configuration;
using System.Threading.Tasks;

namespace Inova.SSO.API.Middlewares
{
    public class UpdateJwtBearerRealmMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IConfiguration _configuration;

        public UpdateJwtBearerRealmMiddleware(RequestDelegate next, IConfiguration configuration)
        {
            _next = next;
            _configuration = configuration;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            // Obter o valor do cabeçalho realm
            string realm = context.Request.Headers["realm"];

            if (realm != null)
            {
                var authority = $"https://sso-inova3d-hml.azurewebsites.net/auth/realms/{realm}";

                var teste = context.RequestServices.GetRequiredService<IOptionsMonitor<JwtBearerOptions>>()
                .Get(JwtBearerDefaults.AuthenticationScheme).Authority;

                context.RequestServices.GetRequiredService<IOptionsMonitor<JwtBearerOptions>>()
                .Get(JwtBearerDefaults.AuthenticationScheme).Authority = authority;

                context.RequestServices.GetRequiredService<IOptionsMonitor<JwtBearerOptions>>()
                    .Get(JwtBearerDefaults.AuthenticationScheme).TokenValidationParameters.ValidIssuer = authority;

                await _next(context);
            }
        }
    }
}

相关问题