.NET 6 中的多租户使用 Keycloak 无需重新启动 .NET 应用程序

问题描述 投票:0回答:1

我正在尝试在 .NET 6 应用程序中实现多租户以授权后端 API。 我通过在 program.cs 文件中的 appSettings.json 和 jwt 模式中添加多个领域信息(发行者和受众)成功实现。 但我的问题是,当.NET 应用程序处于运行状态 时,我想实现相同的多租户,因为我不想在 Keycloak 中创建新领域时重新启动应用程序(生产)

我试图通过 ServiceCollection 将新创建的领域信息注入 JWT Schema 但无法运行它,因为我不允许在应用程序运行时注入新服务。

我也尝试通过中间件来实现它,我能够在运行时添加新的中间件,它具有新创建的领域的模式,但它仍然无法识别模式。

是否可以在不重建应用程序的情况下添加多租户支持?

.net .net-core keycloak multi-tenant keycloak-rest-api
1个回答
0
投票

我也试过中间件,但是没用

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);
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.