Нет Idp с идентификатором объекта http://stubidp.kentor.se/Обнаружена ошибка метаданных в Kentor Auth Services

У нас есть требование включить SAML SSO для входа в мое приложение. Мое приложение представляет собой решение Angular JS + Asp.Net Web API. Мое приложение уже использует аутентификацию носителя Owin в качестве модели авторизации.

Чтобы включить Saml SSO, я экспериментирую с Kentor Auth Services. Но я столкнулся с проблемой, когда Idp вызывает мой webapi. Служба kentor выдает ошибку Данный ключ отсутствует в словаре. Я использую http://stubidp.kentor.se/ для тестирования реализации. Ниже приведена моя конфигурация Saml из начального класса.

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);
            ConfigureOAuth(app);

            var config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseWebApi(config);

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            GlobalConfiguration.Configuration.MessageHandlers.Add(new CachingHandler(GlobalConfiguration.Configuration));
        }
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            var oAuthServerOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/Auth/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new JobPulseAuthorizationServerProvider()
            };
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                            validateInterval: TimeSpan.FromMinutes(30),
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ExternalCookie))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Token Generation
            //app.UseOAuthAuthorizationServer(oAuthServerOptions);
            //app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            app.UseKentorAuthServicesAuthentication(CreateAuthServicesOptions());
        }

        private static KentorAuthServicesAuthenticationOptions CreateAuthServicesOptions()
        {
            var spOptions = GetServiceProviderOptions();
            var authServicesOptions = new KentorAuthServicesAuthenticationOptions(false)
            {
                SPOptions = spOptions
            };

            var idp = new IdentityProvider(new EntityId("~/App_Data/KentorIDPMetadata.xml"), spOptions)
            {
                AllowUnsolicitedAuthnResponse = true,
                Binding = Saml2BindingType.HttpRedirect,
                SingleSignOnServiceUrl = new Uri("http://stubidp.kentor.se/")
            };

            idp.SigningKeys.AddConfiguredKey(
                    new X509Certificate2(fileName: HostingEnvironment.MapPath(
                                    "~/App_Data/Kentor.AuthServices.StubIdp.cer")));

            authServicesOptions.IdentityProviders.Add(idp);

            return authServicesOptions;
        }

        private static SPOptions GetServiceProviderOptions()
        {
            var cultureInfo = CultureInfo.GetCultureInfo("en-US");
            var organization = new Organization
            {
                Names = { new LocalizedName("Kentor", cultureInfo) },
                DisplayNames = { new LocalizedName("Kentor IT AB", cultureInfo) },
                Urls = { new LocalizedUri(new Uri("http://www.kentor.se"), cultureInfo) }
            };
            var spOptions = new SPOptions
            {
                EntityId = new EntityId("http://localhost:53390/AuthServices/acs"),
                ReturnUrl = new Uri("http://localhost:53390/Account/ExternalLoginCallback"),
                Organization = organization
            };
            spOptions.Contacts.Add(new ContactPerson
            {
                Type = ContactType.Technical,
                EmailAddresses = { "[email protected]" }
            });

            spOptions.Contacts.Add(new ContactPerson
            {
                Type = ContactType.Support,
                EmailAddresses = { "[email protected]" }
            });
            var attributeConsumingService = new AttributeConsumingService("AuthServices")
            {
                IsDefault = true,
                RequestedAttributes =
                {
                    new RequestedAttribute("urn:someName")
                    {
                        FriendlyName = "Some Name",
                        IsRequired = true,
                        NameFormat = RequestedAttribute.AttributeNameFormatUri
                    },
                    new RequestedAttribute("Minimal")
                }
            };
            spOptions.AttributeConsumingServices.Add(attributeConsumingService);

            spOptions.ServiceCertificates.Add(new X509Certificate2(
                    AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/App_Data/Kentor.AuthServices.Tests.pfx"));

            return spOptions;
        }

    }

Трассировка стека ошибки

[KeyNotFoundException: The given key was not present in the dictionary.]
   System.Collections.Generic.Dictionary`2.get_Item(TKey key) +11759657
   Kentor.AuthServices.Configuration.IdentityProviderDictionary.get_Item(EntityId entityId) +155

[KeyNotFoundException: No Idp with entity id "http://stubidp.kentor.se/Metadata" found.]
   Kentor.AuthServices.Configuration.IdentityProviderDictionary.get_Item(EntityId entityId) +291
   Kentor.AuthServices.Saml2P.Saml2Response.CheckIfUnsolicitedIsAllowed(IOptions options) +108
   Kentor.AuthServices.Saml2P.Saml2Response.Validate(IOptions options) +37
   Kentor.AuthServices.Saml2P.<CreateClaims>d__53.MoveNext() +170
   System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +381

Не могли бы вы сообщить мне, почему Кентор не смог получить метаданные?


person Umamaheswaran    schedule 04.10.2016    source источник
comment
Всегда полезно перейти к конечной точке метаданных. Например, переход к login.microsoftonline.com/common/.well-known/ показывает, что у вас правильный адрес.   -  person Brent Schmaltz    schedule 04.10.2016


Ответы (1)


Вы путаете идентификатор объекта с путем к метаданным. Метаданные отображаются по адресу, который является идентификатором объекта, но если вы размещаете метаданные локально, вам необходимо их разделить.

var idp = new IdentityProvider(new EntityId("http://stubidp.kentor.se/Metadata"), spOptions)
{
  MetadataLocation = ""~/App_Data/KentorIDPMetadata.xml"
  AllowUnsolicitedAuthnResponse = true,
  // No need to add these if metadata is read.
  // Binding = Saml2BindingType.HttpRedirect,
  // SingleSignOnServiceUrl = new Uri("http://stubidp.kentor.se/")
};

Еще более простой способ — загрузить метаданные непосредственно из idp:

var idp = new IdentityProvider(new EntityId("http://stubidp.kentor.se/Metadata"), spOptions)
{
  LoadMetadata = true,
  AllowUnsolicitedAuthnResponse = true,
};
person Anders Abel    schedule 04.10.2016
comment
Пожалуйста, смотрите обновленный вопрос. Проблема «Нет Idp», похоже, исчезла (спасибо вам). Я столкнулся с еще одной проблемой. Я продолжу проверять это. Между тем, если вы видите очевидную ошибку, пожалуйста, дайте мне знать - person Umamaheswaran; 05.10.2016
comment
Я принял ответ, пожалуйста, найдите мой другой вопрос здесь stackoverflow. com/questions/39867318/ - person Umamaheswaran; 05.10.2016