Пользовательское ПО промежуточного слоя IdentityServer3 OWIN с дополнительными контроллерами MVC

У меня есть реализация Identity Server 3, где в зависимости от запрошенного URL-адреса можно предоставить различные настройки для IDS (настроенные параметры и т. д.).

Это работает нормально, но у меня возникают проблемы с добавлением контроллеров/страниц MVC в приложение (как описано https://github.com/IdentityServer/IdentityServer3/issues/1140) — я получаю исключение 404, когда пытаюсь загрузить новую страницу. Если я заменю coreApp.Use<IdentityServerWithTenantSwitchingMiddleware>(coreApp.Properties); на coreApp.UseIdentityServer(new IdentityServerWithTenantSwitchingMiddleware(null, null).GetOptions());, все будет работать, как и ожидалось, я уверен, что проблемы возникают в моей реализации Invoke в IdentityServerWithTenantSwitchingMiddleware.

Мне кажется, что где-то мне не хватает начальной загрузки/настройки, которая сообщает IDS, что я хочу использовать контроллеры MVC. Или что-то. Я видел пару похожих проблем/вопросов (https://github.com/IdentityServer/IdentityServer3/issues/1934), но ни один из них не относится именно к этой проблеме.

Я воспроизвел эту проблему, используя IdentityServer3 CustomUserService из GitHub — см. мой форк демонстрации CustomUserService (в частности, IdentityServerWithTenantSwitchingMiddleware.cs и Startup.cs). Вы можете увидеть эту проблему, если войдете в демоверсию (пароль/имя пользователя: alice) — она выдает исключение при попытке отобразить страницу eula.

Я включу важные фрагменты кода ниже:

Startup.cs

public void Configuration(IAppBuilder app)
{
    Log.Logger = new LoggerConfiguration()
                   .MinimumLevel.Debug()
                   .WriteTo.Trace()
                   .CreateLogger();

    app.Map("/core", coreApp =>
    {
         coreApp.Use<IdentityServerWithTenantSwitchingMiddleware>(coreApp.Properties);
    });
}

Промежуточное ПО IdentityServerWithTenantSwitching

public override Task Invoke(IOwinContext context)
{
    var app = new AppBuilder();

    //Do some magic based on current request

    var options = GetOptions();

    _properties.ForEach(kvp =>
    {
        if (!app.Properties.ContainsKey(kvp.Key))
        {
            app.Properties.Add(kvp.Key, kvp.Value);
        }
    });

    app.UseIdentityServer(options);
     return app.Build()(context.Environment);
}

private IdentityServerOptions GetOptions()
{
    var factory = new IdentityServerServiceFactory()
        .UseInMemoryClients(Clients.Get())
        .UseInMemoryScopes(Scopes.Get());

    // different examples of custom user services
    var userService = new EulaAtLoginUserService();

    // note: for the sample this registration is a singletone (not what you want in production probably)
    factory.UserService = new Registration<IUserService>(resolver => userService);

    var options = new IdentityServerOptions
    {
        SiteName = "IdentityServer3 - CustomUserService",

        SigningCertificate = Certificate.Get(),
        Factory = factory,

        AuthenticationOptions = new AuthenticationOptions
        {
            LoginPageLinks = new LoginPageLink[] {
                    new LoginPageLink{
                        Text = "Register",
                        Href = "localregistration"
                    }
                }
        },

        EventsOptions = new EventsOptions
        {
            RaiseSuccessEvents = true,
            RaiseErrorEvents = true,
            RaiseFailureEvents = true,
            RaiseInformationEvents = true
        }
    };

    return options;
}

Любая/все помощь/предложения приветствуются.

Алекс


person Alex    schedule 15.02.2018    source источник


Ответы (1)


arrow_upward
0
arrow_downward

Нашла ответ на свой вопрос.

Взято с https://github.com/damianh/DynamicKatanaPipeline — похоже, я не запускал следующие шаги в конвейере. Рабочий код здесь, если кому поможет:

public override Task Invoke(IOwinContext context)
{
    var app = ConfigurePipeline(context);
    var dynamicAppFunc = app.Build();
    return dynamicAppFunc(context.Environment);
}

private IAppBuilder ConfigurePipeline(IOwinContext context)
{
    var app = new AppBuilder();

    app.UseIdentityServer(GetOptions(context));

    app.Run(_next.Invoke);

    return app;
}
person Alex    schedule 19.02.2018