private static void ConfigureRoutes(IdentityServerOptions options, HttpConfiguration config)
 {
     if (options.EnableWelcomePage)
     {
         config.Routes.MapHttpRoute(Constants.RouteNames.Welcome, Constants.RoutePaths.Welcome, new { controller = "Welcome", action = "Get" });
     }
 }
        public static HttpConfiguration Configure(IdentityServerOptions options, ILifetimeScope container)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.SuppressDefaultHostAuthentication();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            config.Services.Add(typeof(IExceptionLogger), new LogProviderExceptionLogger());
            config.Services.Replace(typeof(IHttpControllerTypeResolver), new HttpControllerTypeResolver());
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.LocalOnly;

            if (options.LoggingOptions.EnableWebApiDiagnostics)
            {
                var liblog = new TraceSource("LibLog");
                liblog.Switch.Level = SourceLevels.All;
                liblog.Listeners.Add(new LibLogTraceListener());

                var diag = config.EnableSystemDiagnosticsTracing();
                diag.IsVerbose = options.LoggingOptions.WebApiDiagnosticsIsVerbose;
                diag.TraceSource = liblog;
            }

            ConfigureRoutes(options, config);

            return config;
        }
 internal LastUserNameCookie(IOwinContext ctx, IdentityServerOptions options)
 {
     if (ctx == null) throw new ArgumentNullException("ctx");
     if (options == null) throw new ArgumentNullException("options");
     
     this.ctx = ctx;
     this.options = options;
 }
 public FranceConnectTokenValidator(IdentityServerOptions options, IdentityServerContext context, IClientStore clients, ITokenHandleStore tokenHandles, ICustomTokenValidator customValidator, IEnumerable<IValidationKeysStore> keys, ILogger<TokenValidator> logger)
 {
     _options = options;
     _context = context;
     _clients = clients;
     _tokenHandles = tokenHandles;
     _customValidator = customValidator;
     _keys = keys;
     _logger = logger;
 }
 public MultiTenantEndpointRouter(
     Dictionary<string, EndpointName> pathToNameMap, 
     IdentityServerOptions options, 
     IEnumerable<EndpointMapping> mappings, 
     IOptions<MultiTenantOptions> multiTenantOptionsAccessor,
     ILogger<MultiTenantEndpointRouter> logger
     )
 {
     _pathToNameMap = pathToNameMap;
     _options = options;
     _mappings = mappings;
     _logger = logger;
     multiTenantOptions = multiTenantOptionsAccessor.Value;
 }
        public static HttpConfiguration Configure(IdentityServerOptions options)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.SuppressDefaultHostAuthentication();

            config.MessageHandlers.Insert(0, new KatanaDependencyResolver());
            config.Services.Add(typeof(IExceptionLogger), new LogProviderExceptionLogger());

            config.Formatters.Remove(config.Formatters.XmlFormatter);

            if (options.EnableWebApiDiagnostics)
            {
                config.EnableSystemDiagnosticsTracing();
            }

            return config;
        }
 public BasicAuthenticationSecretParsing()
 {
     _options = new IdentityServerOptions();
     _parser  = new BasicAuthenticationSecretParser(_options, TestLogger.Create <BasicAuthenticationSecretParser>());
 }
Exemple #8
0
        public static TokenRequestValidator CreateTokenRequestValidator(
            IdentityServerOptions options                          = null,
            IIssuerNameService issuerNameService                   = null,
            IResourceStore resourceStore                           = null,
            IAuthorizationCodeStore authorizationCodeStore         = null,
            IRefreshTokenStore refreshTokenStore                   = null,
            IResourceOwnerPasswordValidator resourceOwnerValidator = null,
            IProfileService profile = null,
            IDeviceCodeValidator deviceCodeValidator = null,
            IEnumerable <IExtensionGrantValidator> extensionGrantValidators = null,
            ICustomTokenRequestValidator customRequestValidator             = null,
            IRefreshTokenService refreshTokenService = null,
            IResourceValidator resourceValidator     = null)
        {
            if (options == null)
            {
                options = TestIdentityServerOptions.Create();
            }

            if (issuerNameService == null)
            {
                issuerNameService = new TestIssuerNameService(options.IssuerUri);
            }

            if (resourceStore == null)
            {
                resourceStore = new InMemoryResourcesStore(TestScopes.GetIdentity(), TestScopes.GetApis(), TestScopes.GetScopes());
            }

            if (resourceOwnerValidator == null)
            {
                resourceOwnerValidator = new TestResourceOwnerPasswordValidator();
            }

            if (profile == null)
            {
                profile = new TestProfileService();
            }

            if (deviceCodeValidator == null)
            {
                deviceCodeValidator = new TestDeviceCodeValidator();
            }

            if (customRequestValidator == null)
            {
                customRequestValidator = new DefaultCustomTokenRequestValidator();
            }

            ExtensionGrantValidator aggregateExtensionGrantValidator;

            if (extensionGrantValidators == null)
            {
                aggregateExtensionGrantValidator = new ExtensionGrantValidator(new[] { new TestGrantValidator() }, TestLogger.Create <ExtensionGrantValidator>());
            }
            else
            {
                aggregateExtensionGrantValidator = new ExtensionGrantValidator(extensionGrantValidators, TestLogger.Create <ExtensionGrantValidator>());
            }

            if (authorizationCodeStore == null)
            {
                authorizationCodeStore = CreateAuthorizationCodeStore();
            }

            if (refreshTokenStore == null)
            {
                refreshTokenStore = CreateRefreshTokenStore();
            }

            if (resourceValidator == null)
            {
                resourceValidator = CreateResourceValidator(resourceStore);
            }

            if (refreshTokenService == null)
            {
                refreshTokenService = CreateRefreshTokenService(
                    refreshTokenStore,
                    profile);
            }

            return(new TokenRequestValidator(
                       options,
                       issuerNameService,
                       authorizationCodeStore,
                       resourceOwnerValidator,
                       profile,
                       deviceCodeValidator,
                       aggregateExtensionGrantValidator,
                       customRequestValidator,
                       resourceValidator,
                       resourceStore,
                       refreshTokenService,
                       new TestEventService(),
                       new StubClock(),
                       TestLogger.Create <TokenRequestValidator>()));
        }
        private static void ConfigureRoutes(IdentityServerOptions options, HttpConfiguration config)
        {
            if (options.EnableWelcomePage)
            {
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Welcome, 
                    Constants.RoutePaths.Welcome, 
                    new { controller = "Welcome", action = "Get" });
            }

            if (options.Endpoints.EnableAccessTokenValidationEndpoint)
            {
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Oidc.AccessTokenValidation,
                    Constants.RoutePaths.Oidc.AccessTokenValidation,
                    new { controller = "AccessTokenValidation" });
            }

            if (options.Endpoints.EnableIntrospectionEndpoint)
            {
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Oidc.Introspection,
                    Constants.RoutePaths.Oidc.Introspection,
                    new { controller = "IntrospectionEndpoint" });
            }

            if (options.Endpoints.EnableAuthorizeEndpoint)
            {
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Oidc.Authorize,
                    Constants.RoutePaths.Oidc.Authorize,
                    new { controller = "AuthorizeEndpoint", action = "Get" });
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Oidc.Consent,
                    Constants.RoutePaths.Oidc.Consent,
                    new { controller = "AuthorizeEndpoint", action = "PostConsent" });
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Oidc.SwitchUser,
                    Constants.RoutePaths.Oidc.SwitchUser,
                    new { controller = "AuthorizeEndpoint", action = "LoginAsDifferentUser" });
            }

            if (options.Endpoints.EnableCheckSessionEndpoint)
            {
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Oidc.CheckSession,
                    Constants.RoutePaths.Oidc.CheckSession,
                    new { controller = "CheckSessionEndpoint" });
            }

            if (options.Endpoints.EnableClientPermissionsEndpoint)
            {
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.ClientPermissions,
                    Constants.RoutePaths.ClientPermissions,
                    new { controller = "ClientPermissions" });
            }

            if (options.Endpoints.EnableCspReportEndpoint)
            {
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.CspReport,
                    Constants.RoutePaths.CspReport,
                    new { controller = "CspReport" });
            }

            if (options.Endpoints.EnableDiscoveryEndpoint)
            {
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Oidc.DiscoveryConfiguration,
                    Constants.RoutePaths.Oidc.DiscoveryConfiguration,
                    new { controller = "DiscoveryEndpoint", action = "GetConfiguration" });
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Oidc.DiscoveryWebKeys,
                    Constants.RoutePaths.Oidc.DiscoveryWebKeys,
                    new { controller = "DiscoveryEndpoint", action= "GetKeyData" });
            }

            if (options.Endpoints.EnableEndSessionEndpoint)
            {
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Oidc.EndSession,
                    Constants.RoutePaths.Oidc.EndSession,
                    new { controller = "EndSession", action = "Logout" });
            }
            
            // this one is always enabled/allowed (for use by our logout page)
            config.Routes.MapHttpRoute(
                Constants.RouteNames.Oidc.EndSessionCallback,
                Constants.RoutePaths.Oidc.EndSessionCallback,
                new { controller = "EndSession", action = "LogoutCallback" });

            if (options.Endpoints.EnableIdentityTokenValidationEndpoint)
            {
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Oidc.IdentityTokenValidation,
                    Constants.RoutePaths.Oidc.IdentityTokenValidation,
                    new { controller = "IdentityTokenValidation" });
            }

            if (options.Endpoints.EnableTokenEndpoint)
            {
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Oidc.Token,
                    Constants.RoutePaths.Oidc.Token,
                    new { controller = "TokenEndpoint", action= "Post" });
            }

            if (options.Endpoints.EnableTokenRevocationEndpoint)
            {
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Oidc.Revocation,
                    Constants.RoutePaths.Oidc.Revocation,
                    new { controller = "RevocationEndpoint", action = "Post" });
            }

            if (options.Endpoints.EnableUserInfoEndpoint)
            {
                config.Routes.MapHttpRoute(
                    Constants.RouteNames.Oidc.UserInfo,
                    Constants.RoutePaths.Oidc.UserInfo,
                    new { controller = "UserInfoEndpoint" });
            }
        }
Exemple #10
0
        public static TokenRequestValidator CreateTokenRequestValidator(
            IdentityServerOptions options = null,
            IResourceStore resourceStore  = null,
            IAuthorizationCodeStore authorizationCodeStore         = null,
            IRefreshTokenStore refreshTokenStore                   = null,
            IResourceOwnerPasswordValidator resourceOwnerValidator = null,
            IProfileService profile = null,
            IEnumerable <IExtensionGrantValidator> extensionGrantValidators = null,
            ICustomTokenRequestValidator customRequestValidator             = null,
            ScopeValidator scopeValidator = null)
        {
            if (options == null)
            {
                options = TestIdentityServerOptions.Create();
            }

            if (resourceStore == null)
            {
                resourceStore = new InMemoryResourcesStore(TestScopes.GetIdentity(), TestScopes.GetApis());
            }

            if (resourceOwnerValidator == null)
            {
                resourceOwnerValidator = new TestResourceOwnerPasswordValidator();
            }

            if (profile == null)
            {
                profile = new TestProfileService();
            }

            if (customRequestValidator == null)
            {
                customRequestValidator = new DefaultCustomTokenRequestValidator();
            }

            ExtensionGrantValidator aggregateExtensionGrantValidator;

            if (extensionGrantValidators == null)
            {
                aggregateExtensionGrantValidator = new ExtensionGrantValidator(new[] { new TestGrantValidator() }, TestLogger.Create <ExtensionGrantValidator>());
            }
            else
            {
                aggregateExtensionGrantValidator = new ExtensionGrantValidator(extensionGrantValidators, TestLogger.Create <ExtensionGrantValidator>());
            }

            if (authorizationCodeStore == null)
            {
                authorizationCodeStore = CreateAuthorizationCodeStore();
            }

            if (refreshTokenStore == null)
            {
                refreshTokenStore = CreateRefreshTokenStore();
            }

            if (scopeValidator == null)
            {
                scopeValidator = new ScopeValidator(resourceStore, new LoggerFactory().CreateLogger <ScopeValidator>());
            }

            return(new TokenRequestValidator(
                       options,
                       authorizationCodeStore,
                       refreshTokenStore,
                       resourceOwnerValidator,
                       profile,
                       aggregateExtensionGrantValidator,
                       customRequestValidator,
                       scopeValidator,
                       new TestEventService(),
                       TestLogger.Create <TokenRequestValidator>()));
        }
Exemple #11
0
 void Init(HttpContext context)
 {
     _clientList         = _clientList ?? context.RequestServices.GetRequiredService <IClientSessionService>();
     _logoutMessageStore = _logoutMessageStore ?? context.RequestServices.GetRequiredService <IMessageStore <LogoutMessage> >();
     _options            = _options ?? context.RequestServices.GetRequiredService <IdentityServerOptions>();
 }
 private void Init(HttpContext context)
 {
     _options = _options ?? context.RequestServices.GetRequiredService <IdentityServerOptions>();
     _authorizationParametersMessageStore = _authorizationParametersMessageStore ?? context.RequestServices.GetService <IAuthorizationParametersMessageStore>();
 }
Exemple #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultTokenCreationService"/> class.
 /// </summary>
 /// <param name="options">The options.</param>
 /// <param name="keys">The keys.</param>
 /// <param name="logger">The logger.</param>
 public DefaultTokenCreationService(IdentityServerOptions options, IKeyMaterialService keys, ILogger <DefaultTokenCreationService> logger)
 {
     Options = options;
     Keys    = keys;
     Logger  = logger;
 }
        public virtual void Configure(IAppBuilder owinApp)
        {
            if (owinApp == null)
            {
                throw new ArgumentNullException(nameof(owinApp));
            }

            owinApp.Map("/core", coreApp =>
            {
                LogProvider.SetCurrentLogProvider(DependencyManager.Resolve <ILogProvider>());

                IdentityServerServiceFactory factory = new IdentityServerServiceFactory()
                                                       .UseInMemoryClients(DependencyManager.Resolve <IOAuthClientsProvider>().GetClients().ToArray())
                                                       .UseInMemoryScopes(ScopesProvider.GetScopes());

                IUserService ResolveUserService(IdentityServer3.Core.Services.IDependencyResolver resolver)
                {
                    OwinEnvironmentService owinEnv = resolver.Resolve <OwinEnvironmentService>();
                    IOwinContext owinContext       = new OwinContext(owinEnv.Environment);
                    IUserService userService       = owinContext.GetDependencyResolver().Resolve <IUserService>();

                    if (userService is UserService bitUserService)
                    {
                        bitUserService.CurrentCancellationToken = owinContext.Request.CallCancelled;
                    }

                    return(userService);
                }

                factory.UserService = new Registration <IUserService>(ResolveUserService);

                factory.EventService = new Registration <IEventService>(EventService);

                IViewService ResolveViewService(IdentityServer3.Core.Services.IDependencyResolver resolver)
                {
                    OwinEnvironmentService owinEnv = resolver.Resolve <OwinEnvironmentService>();
                    IOwinContext owinContext       = new OwinContext(owinEnv.Environment);
                    return(owinContext.GetDependencyResolver().Resolve <IViewService>());
                }

                factory.ViewService = new Registration <IViewService>(ResolveViewService);

                factory.RedirectUriValidator = new Registration <IRedirectUriValidator>(RedirectUriValidator);

                bool requireSslConfigValue = AppEnvironment.GetConfig("RequireSsl", defaultValueOnNotFound: false);

                string identityServerSiteName = AppEnvironment.GetConfig("IdentityServerSiteName", $"{AppEnvironment.AppInfo.Name} Identity Server");

                IdentityServerOptions identityServerOptions = new IdentityServerOptions
                {
                    SiteName           = identityServerSiteName,
                    SigningCertificate = AppCertificatesProvider.GetSingleSignOnCertificate(),
                    Factory            = factory,
                    RequireSsl         = requireSslConfigValue,
                    EnableWelcomePage  = AppEnvironment.DebugMode == true,
                    IssuerUri          = AppEnvironment.GetSsoIssuerName(),
                    CspOptions         = new CspOptions
                    {
                        // Content security policy
                        Enabled = false
                    },
                    Endpoints = new EndpointOptions
                    {
                        EnableAccessTokenValidationEndpoint   = true,
                        EnableAuthorizeEndpoint               = true,
                        EnableCheckSessionEndpoint            = true,
                        EnableClientPermissionsEndpoint       = true,
                        EnableCspReportEndpoint               = true,
                        EnableDiscoveryEndpoint               = true,
                        EnableEndSessionEndpoint              = true,
                        EnableIdentityTokenValidationEndpoint = true,
                        EnableIntrospectionEndpoint           = true,
                        EnableTokenEndpoint           = true,
                        EnableTokenRevocationEndpoint = true,
                        EnableUserInfoEndpoint        = true
                    },
                    EventsOptions = new EventsOptions
                    {
                        RaiseErrorEvents   = true,
                        RaiseFailureEvents = true
                    },
                    AuthenticationOptions = new AuthenticationOptions
                    {
                        IdentityProviders = ConfigureIdentityProviders
                    }
                };

                foreach (IIdentityServerOptionsCustomizer customizer in Customizers)
                {
                    customizer.Customize(identityServerOptions);
                }

                coreApp.UseIdentityServer(identityServerOptions);
            });
        }
    /// <summary>
    /// ctor
    /// </summary>
    /// <param name="httpContextAccessor"></param>
    /// <param name="identityServerOptions"></param>
    /// <param name="options"></param>
    public PostConfigureApplicationCookieTicketStore(IHttpContextAccessor httpContextAccessor, IdentityServerOptions identityServerOptions, IOptions <Microsoft.AspNetCore.Authentication.AuthenticationOptions> options)
    {
        _httpContextAccessor = httpContextAccessor;

        _scheme = identityServerOptions.Authentication.CookieAuthenticationScheme ??
                  options.Value.DefaultAuthenticateScheme ??
                  options.Value.DefaultScheme;
    }
        public Startup(IHostingEnvironment env)
        {
            // Load all the configuration information from the "json" file & the environment variables.
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json")
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                          .AddEnvironmentVariables();

            Configuration          = builder.Build();
            _authenticationOptions = new AuthenticationMiddlewareOptions
            {
                IdServer = new IdServerOptions
                {
                    ExternalLoginCallback = "/Authenticate/LoginCallback",
                    LoginUrls             = new List <string>
                    {
                        "/Authenticate",
                        "/Authenticate/ExternalLogin",
                        "/Authenticate/OpenId",
                        "/Authenticate/LocalLoginOpenId",
                        "/Authenticate/LocalLogin",
                        "/Authenticate/ExternalLoginOpenId"
                    }
                },
                ConfigurationEdp = new ConfigurationEdpOptions
                {
                    ConfigurationUrl = Configuration["ConfigurationEdp:Url"],
                    ClientId         = Configuration["ConfigurationEdp:ClientId"],
                    ClientSecret     = Configuration["ConfigurationEdp:ClientSecret"],
                    Scopes           = new List <string>
                    {
                        "display_configuration"
                    }
                }
            };
            var twoFactorServiceStore = new TwoFactorServiceStore();
            var factory = new SimpleIdServerConfigurationClientFactory();

            twoFactorServiceStore.Add(new DefaultTwilioSmsService(factory, Configuration["ConfigurationEdp:Url"]));
            twoFactorServiceStore.Add(new DefaultEmailService(factory, Configuration["ConfigurationEdp:Url"]));
            _options = new IdentityServerOptions
            {
                IsDeveloperModeEnabled = false,
                DataSource             = new DataSourceOptions
                {
                    IsOpenIdDataMigrated   = true,
                    IsEvtStoreDataMigrated = true,
                },
                Logging = new LoggingOptions
                {
                    ElasticsearchOptions = new ElasticsearchOptions(),
                    FileLogOptions       = new FileLogOptions()
                },
                Authenticate = new AuthenticateOptions
                {
                    CookieName = Constants.CookieName
                },
                Scim = new ScimOptions
                {
                    IsEnabled = true,
                    EndPoint  = "http://localhost:5555/"
                },
                TwoFactorServiceStore = twoFactorServiceStore
            };

            var openIdType   = Configuration["Db:OpenIdType"];
            var evtStoreType = Configuration["Db:EvtStoreType"];

            if (string.Equals(openIdType, "SQLSERVER", System.StringComparison.CurrentCultureIgnoreCase))
            {
                _options.DataSource.OpenIdDataSourceType   = DataSourceTypes.SqlServer;
                _options.DataSource.OpenIdConnectionString = Configuration["Db:OpenIdConnectionString"];
            }
            else if (string.Equals(openIdType, "SQLITE", System.StringComparison.CurrentCultureIgnoreCase))
            {
                _options.DataSource.OpenIdDataSourceType   = DataSourceTypes.SqlLite;
                _options.DataSource.OpenIdConnectionString = Configuration["Db:OpenIdConnectionString"];
            }
            else if (string.Equals(openIdType, "POSTGRE", System.StringComparison.CurrentCultureIgnoreCase))
            {
                _options.DataSource.OpenIdDataSourceType   = DataSourceTypes.Postgre;
                _options.DataSource.OpenIdConnectionString = Configuration["Db:OpenIdConnectionString"];
            }
            else
            {
                _options.DataSource.OpenIdDataSourceType = DataSourceTypes.InMemory;
            }

            if (string.Equals(evtStoreType, "SQLSERVER", System.StringComparison.CurrentCultureIgnoreCase))
            {
                _options.DataSource.EvtStoreDataSourceType   = DataSourceTypes.SqlServer;
                _options.DataSource.EvtStoreConnectionString = Configuration["Db:EvtStoreConnectionString"];
            }
            else if (string.Equals(evtStoreType, "SQLITE", System.StringComparison.CurrentCultureIgnoreCase))
            {
                _options.DataSource.EvtStoreDataSourceType   = DataSourceTypes.SqlLite;
                _options.DataSource.EvtStoreConnectionString = Configuration["Db:EvtStoreConnectionString"];
            }
            else if (string.Equals(evtStoreType, "POSTGRE", System.StringComparison.CurrentCultureIgnoreCase))
            {
                _options.DataSource.EvtStoreDataSourceType   = DataSourceTypes.Postgre;
                _options.DataSource.EvtStoreConnectionString = Configuration["Db:EvtStoreConnectionString"];
            }
            else
            {
                _options.DataSource.EvtStoreDataSourceType = DataSourceTypes.InMemory;
            }

            bool isLogFileEnabled,
                 isElasticSearchEnabled;

            if (bool.TryParse(Configuration["Log:File:Enabled"], out isLogFileEnabled))
            {
                _options.Logging.FileLogOptions.IsEnabled = isLogFileEnabled;
                if (isLogFileEnabled)
                {
                    _options.Logging.FileLogOptions.PathFormat = Configuration["Log:File:PathFormat"];
                }
            }

            if (bool.TryParse(Configuration["Log:Elasticsearch:Enabled"], out isElasticSearchEnabled))
            {
                _options.Logging.ElasticsearchOptions.IsEnabled = isElasticSearchEnabled;
                if (isElasticSearchEnabled)
                {
                    _options.Logging.ElasticsearchOptions.Url = Configuration["Log:Elasticsearch:Url"];
                }
            }
        }
 internal AntiForgeryToken(IOwinContext context, IdentityServerOptions options)
 {
     this.context = context;
     this.options = options;
 }
Exemple #18
0
 public AuthorizeRedirectResult(AuthorizeResponse response, IdentityServerOptions options)
 {
     _response = response;
     _options  = options;
 }
 public DefaultTokenSigningService(IdentityServerOptions options)
 {
     _options = options;
 }
        public static IContainer Configure(IdentityServerOptions options)
        {
            if (options == null) throw new ArgumentNullException("options");
            if (options.Factory == null) throw new InvalidOperationException("null factory");

            IdentityServerServiceFactory fact = options.Factory;
            fact.Validate();

            var builder = new ContainerBuilder();

            builder.RegisterInstance(options).AsSelf();

            // mandatory from factory
            builder.Register(fact.UserService, "inner");
            builder.RegisterDecorator<IUserService>((s, inner) =>
            {
                var filter = s.Resolve<IExternalClaimsFilter>();
                return new ExternalClaimsFilterUserService(filter, inner);
            }, "inner");

            builder.Register(fact.ScopeStore);
            builder.Register(fact.ClientStore);
            
            // optional from factory
            if (fact.AuthorizationCodeStore != null)
            {
                builder.Register(fact.AuthorizationCodeStore, "inner");
            }
            else
            {
                var inmemCodeStore = new InMemoryAuthorizationCodeStore();
                builder.RegisterInstance(inmemCodeStore).Named<IAuthorizationCodeStore>("inner");
            }
            builder.RegisterDecorator<IAuthorizationCodeStore>((s, inner) =>
            {
                return new KeyHashingAuthorizationCodeStore(inner);
            }, "inner");

            if (fact.TokenHandleStore != null)
            {
                builder.Register(fact.TokenHandleStore, "inner");
            }
            else
            {
                var inmemTokenHandleStore = new InMemoryTokenHandleStore();
                builder.RegisterInstance(inmemTokenHandleStore).Named<ITokenHandleStore>("inner");
            }
            builder.RegisterDecorator<ITokenHandleStore>((s, inner) =>
            {
                return new KeyHashingTokenHandleStore(inner);
            }, "inner");

            if (fact.RefreshTokenStore != null)
            {
                builder.Register(fact.RefreshTokenStore, "inner");
            }
            else
            {
                var inmemRefreshTokenStore = new InMemoryRefreshTokenStore();
                builder.RegisterInstance(inmemRefreshTokenStore).Named<IRefreshTokenStore>("inner");
            }
            builder.RegisterDecorator<IRefreshTokenStore>((s, inner) =>
            {
                return new KeyHashingRefreshTokenStore(inner);
            }, "inner");

            if (fact.ConsentStore != null)
            {
                builder.Register(fact.ConsentStore);
            }
            else
            {
                var inmemConsentStore = new InMemoryConsentStore();
                builder.RegisterInstance(inmemConsentStore).As<IConsentStore>();
            }

            if (fact.ClaimsProvider != null)
            {
                builder.Register(fact.ClaimsProvider);
            }
            else
            {
                builder.RegisterType<DefaultClaimsProvider>().As<IClaimsProvider>();
            }

            if (fact.TokenService != null)
            {
                builder.Register(fact.TokenService);
            }
            else
            {
                builder.RegisterType<DefaultTokenService>().As<ITokenService>();
            }

            if (fact.RefreshTokenService != null)
            {
                builder.Register(fact.RefreshTokenService);
            }
            else
            {
                builder.RegisterType<DefaultRefreshTokenService>().As<IRefreshTokenService>();
            }

            if (fact.TokenSigningService != null)
            {
                builder.Register(fact.TokenSigningService);
            }
            else
            {
                builder.RegisterType<DefaultTokenSigningService>().As<ITokenSigningService>();
            }

            if (fact.CustomRequestValidator != null)
            {
                builder.Register(fact.CustomRequestValidator);
            }
            else
            {
                builder.RegisterType<DefaultCustomRequestValidator>().As<ICustomRequestValidator>();
            }

            if (fact.CustomGrantValidator != null)
            {
                builder.Register(fact.CustomGrantValidator);
            }
            else
            {
                builder.RegisterType<DefaultCustomGrantValidator>().As<ICustomGrantValidator>();
            }

            if (fact.ExternalClaimsFilter != null)
            {
                builder.Register(fact.ExternalClaimsFilter);
            }
            else
            {
                builder.RegisterType<NopClaimsFilter>().As<IExternalClaimsFilter>();
            }

            if (fact.CustomTokenValidator != null)
            {
                builder.Register(fact.CustomTokenValidator);
            }
            else
            {
                builder.RegisterType<DefaultCustomTokenValidator>().As<ICustomTokenValidator>();
            }

            if (fact.ConsentService != null)
            {
                builder.Register(fact.ConsentService);
            }
            else
            {
                builder.RegisterType<DefaultConsentService>().As<IConsentService>();
            }

            if (fact.EventService != null)
            {
                builder.Register(fact.EventService);
            }
            else
            {
                builder.RegisterType<DefaultEventService>().As<IEventService>();
            }

            if (fact.RedirectUriValidator != null)
            {
                builder.Register(fact.RedirectUriValidator);
            }
            else
            {
                builder.RegisterType<DefaultRedirectUriValidator>().As<IRedirectUriValidator>();
            }

            // this is more of an internal interface, but maybe we want to open it up as pluggable?
            // this is used by the DefaultClientPermissionsService below, or it could be used
            // by a custom IClientPermissionsService
            builder.Register(ctx =>
            {
                var consent = ctx.Resolve<IConsentStore>();
                var refresh = ctx.Resolve<IRefreshTokenStore>();
                var code = ctx.Resolve<IAuthorizationCodeStore>();
                var access = ctx.Resolve<ITokenHandleStore>();
                return new AggregatePermissionsStore(
                    consent,
                    new TokenMetadataPermissionsStoreAdapter(refresh.GetAllAsync, refresh.RevokeAsync),
                    new TokenMetadataPermissionsStoreAdapter(code.GetAllAsync, code.RevokeAsync),
                    new TokenMetadataPermissionsStoreAdapter(access.GetAllAsync, access.RevokeAsync)
                );
            }).As<IPermissionsStore>();

            if (fact.ClientPermissionsService != null)
            {
                builder.Register(fact.ClientPermissionsService);
            }
            else
            {
                builder.RegisterType<DefaultClientPermissionsService>().As<IClientPermissionsService>();
            }

            if (fact.ViewService != null)
            {
                builder.Register(fact.ViewService);
            }
            else
            {
                builder.RegisterType<DefaultViewService>().As<IViewService>();
            }

            // hosting services
            builder.RegisterType<OwinEnvironmentService>();

            // validators
            builder.RegisterType<TokenRequestValidator>();
            builder.RegisterType<AuthorizeRequestValidator>();
            builder.RegisterType<ClientValidator>();
            builder.RegisterType<TokenValidator>();
            builder.RegisterType<EndSessionRequestValidator>();
            builder.RegisterType<BearerTokenUsageValidator>();
            builder.RegisterType<ScopeValidator>();

            // processors
            builder.RegisterType<TokenResponseGenerator>();
            builder.RegisterType<AuthorizeResponseGenerator>();
            builder.RegisterType<AuthorizeInteractionResponseGenerator>();
            builder.RegisterType<UserInfoResponseGenerator>();
            builder.RegisterType<EndSessionResponseGenerator>();

            // for authentication
            var authenticationOptions = options.AuthenticationOptions ?? new AuthenticationOptions();
            builder.RegisterInstance(authenticationOptions).AsSelf();

            // load core controller
            builder.RegisterApiControllers(typeof(AuthorizeEndpointController).Assembly);

            // add any additional dependencies from hosting application
            foreach(var registration in fact.Registrations)
            {
                builder.Register(registration);
            }

            return builder.Build();
        }
Exemple #21
0
        public static IContainer Configure(IdentityServerOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (options.Factory == null)
            {
                throw new InvalidOperationException("null factory");
            }

            IdentityServerServiceFactory fact = options.Factory;

            fact.Validate();

            var builder = new ContainerBuilder();

            builder.RegisterInstance(options).AsSelf();

            // mandatory from factory
            builder.Register(fact.ScopeStore);
            builder.Register(fact.ClientStore);
            builder.RegisterDecorator <IUserService, ExternalClaimsFilterUserService>(fact.UserService);

            // optional from factory
            builder.RegisterDecoratorDefaultInstance <IAuthorizationCodeStore, KeyHashingAuthorizationCodeStore, InMemoryAuthorizationCodeStore>(fact.AuthorizationCodeStore);
            builder.RegisterDecoratorDefaultInstance <ITokenHandleStore, KeyHashingTokenHandleStore, InMemoryTokenHandleStore>(fact.TokenHandleStore);
            builder.RegisterDecoratorDefaultInstance <IRefreshTokenStore, KeyHashingRefreshTokenStore, InMemoryRefreshTokenStore>(fact.RefreshTokenStore);
            builder.RegisterDefaultInstance <IConsentStore, InMemoryConsentStore>(fact.ConsentStore);
            builder.RegisterDefaultType <IClaimsProvider, DefaultClaimsProvider>(fact.ClaimsProvider);
            builder.RegisterDefaultType <ITokenService, DefaultTokenService>(fact.TokenService);
            builder.RegisterDefaultType <IRefreshTokenService, DefaultRefreshTokenService>(fact.RefreshTokenService);
            builder.RegisterDefaultType <ITokenSigningService, DefaultTokenSigningService>(fact.TokenSigningService);
            builder.RegisterDefaultType <ICustomRequestValidator, DefaultCustomRequestValidator>(fact.CustomRequestValidator);
            builder.RegisterDefaultType <ICustomGrantValidator, DefaultCustomGrantValidator>(fact.CustomGrantValidator);
            builder.RegisterDefaultType <IExternalClaimsFilter, NopClaimsFilter>(fact.ExternalClaimsFilter);
            builder.RegisterDefaultType <ICustomTokenValidator, DefaultCustomTokenValidator>(fact.CustomTokenValidator);
            builder.RegisterDefaultType <IConsentService, DefaultConsentService>(fact.ConsentService);

            builder.RegisterDecoratorDefaultType <IEventService, EventServiceDecorator, DefaultEventService>(fact.EventService);

            builder.RegisterDefaultType <IRedirectUriValidator, DefaultRedirectUriValidator>(fact.RedirectUriValidator);
            builder.RegisterDefaultType <ILocalizationService, DefaultLocalizationService>(fact.LocalizationService);
            builder.RegisterDefaultType <IClientPermissionsService, DefaultClientPermissionsService>(fact.ClientPermissionsService);
            builder.RegisterDefaultType <IViewService, DefaultViewService>(fact.ViewService);
            builder.RegisterDefaultType <IClientSecretValidator, HashedClientSecretValidator>(fact.ClientSecretValidator);

            // this is more of an internal interface, but maybe we want to open it up as pluggable?
            // this is used by the DefaultClientPermissionsService below, or it could be used
            // by a custom IClientPermissionsService
            builder.Register(ctx =>
            {
                var consent = ctx.Resolve <IConsentStore>();
                var refresh = ctx.Resolve <IRefreshTokenStore>();
                var code    = ctx.Resolve <IAuthorizationCodeStore>();
                var access  = ctx.Resolve <ITokenHandleStore>();
                return(new AggregatePermissionsStore(
                           consent,
                           new TokenMetadataPermissionsStoreAdapter(refresh.GetAllAsync, refresh.RevokeAsync),
                           new TokenMetadataPermissionsStoreAdapter(code.GetAllAsync, code.RevokeAsync),
                           new TokenMetadataPermissionsStoreAdapter(access.GetAllAsync, access.RevokeAsync)
                           ));
            }).As <IPermissionsStore>();

            // hosting services
            builder.RegisterType <OwinEnvironmentService>();

            // validators
            builder.RegisterType <TokenRequestValidator>();
            builder.RegisterType <AuthorizeRequestValidator>();
            builder.RegisterType <ClientValidator>();
            builder.RegisterType <TokenValidator>();
            builder.RegisterType <EndSessionRequestValidator>();
            builder.RegisterType <BearerTokenUsageValidator>();
            builder.RegisterType <ScopeValidator>();

            // processors
            builder.RegisterType <TokenResponseGenerator>();
            builder.RegisterType <AuthorizeResponseGenerator>();
            builder.RegisterType <AuthorizeInteractionResponseGenerator>();
            builder.RegisterType <UserInfoResponseGenerator>();
            builder.RegisterType <EndSessionResponseGenerator>();

            // for authentication
            var authenticationOptions = options.AuthenticationOptions ?? new AuthenticationOptions();

            builder.RegisterInstance(authenticationOptions).AsSelf();

            // load core controller
            builder.RegisterApiControllers(typeof(AuthorizeEndpointController).Assembly);

            // other internal
            builder.Register(c => new OwinEnvironmentService(c.Resolve <IOwinContext>()));
            builder.Register(c => new SessionCookie(c.Resolve <IOwinContext>(), c.Resolve <IdentityServerOptions>()));
            builder.Register(c => new MessageCookie <SignInMessage>(c.Resolve <IOwinContext>(), c.Resolve <IdentityServerOptions>()));
            builder.Register(c => new MessageCookie <SignOutMessage>(c.Resolve <IOwinContext>(), c.Resolve <IdentityServerOptions>()));
            builder.Register(c => new LastUserNameCookie(c.Resolve <IOwinContext>(), c.Resolve <IdentityServerOptions>()));
            builder.Register(c => new AntiForgeryToken(c.Resolve <IOwinContext>(), c.Resolve <IdentityServerOptions>()));

            // add any additional dependencies from hosting application
            foreach (var registration in fact.Registrations)
            {
                builder.Register(registration, registration.Name);
            }

            return(builder.Build());
        }
 public ClientListCookie(IOwinContext ctx, IdentityServerOptions options)
 {
     this.ctx = ctx;
     this.options = options;
 }
 public ClientListCookie(IOwinContext ctx, IdentityServerOptions options)
 {
     this.ctx     = ctx;
     this.options = options;
 }
 public AlwaysInvalidAccessTokenValidator(IdentityServerOptions options, IClientStore clients, ITokenHandleStore tokenHandles, ICustomTokenValidator customValidator, OwinEnvironmentService context)
     : base(options, clients, tokenHandles, customValidator, context, new DefaultSigningKeyService(options))
 {
 }
 public TokenIssuerService(ITokenService tokenService, IdentityServerOptions options, IOptions <AuthorizationConfigs> authConfig)
 {
     _tokenService          = tokenService;
     _identityServerOptions = options;
     _autorizationOptions   = authConfig.Value;
 }
Exemple #26
0
 // todo: remove in next major version
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultTokenSigningService"/> class.
 /// </summary>
 /// <param name="options">The options.</param>
 public DefaultTokenSigningService(IdentityServerOptions options)
 {
     _options    = options;
     _keyService = new DefaultSigningKeyService(options);
 }
Exemple #27
0
        public void Configuration(IAppBuilder app)
        {
#if DEBUG
            const string serverName = "devservername";
#else
            const string serverName = "prodservername";
#endif

            LogProvider.SetCurrentLogProvider(new TraceSourceLogProvider());


            const string connectionName = "AspId";

            var factory = new IdentityServerServiceFactory();
            factory.ConfigureClientService(connectionName);
            factory.ConfigureScopeService(connectionName);
            factory.ConfigureUserService(connectionName);
            //factory.ConfigureClientStoreCache();
            //factory.ConfigureScopeStoreCache();
            //factory.ConfigureUserServiceCache();

            app.Map("/core1", coreApp =>
            {
                var options = new IdentityServerOptions
                {
                    IssuerUri             = "https://" + serverName + "/identityserver",
                    SiteName              = "Identity Server Name",
                    SigningCertificate    = Cert.Load(serverName),
                    Factory               = factory,
                    CorsPolicy            = CorsPolicy.AllowAll,
                    RequireSsl            = true,
                    EnableWelcomePage     = true,
                    AuthenticationOptions = new AuthenticationOptions
                    {
                        EnableLoginHint                           = true,
                        EnableSignOutPrompt                       = false,
                        EnableLocalLogin                          = false,
                        EnablePostSignOutAutoRedirect             = true,
                        PostSignOutAutoRedirectDelay              = 0,
                        RequireAuthenticatedUserForSignOutMessage = false,
                        RememberLastUsername                      = false,
                        SignInMessageThreshold                    = 3,
                        IdentityProviders                         = ConfigureAdditionalIdentityProviders1,
                        CookieOptions = new Thinktecture.IdentityServer.Core.Configuration.CookieOptions()
                        {
                            Prefix     = "Core1",
                            SecureMode = CookieSecureMode.Always
                        }
                    },
                    LoggingOptions = new LoggingOptions
                    {
                        EnableHttpLogging          = true,
                        EnableWebApiDiagnostics    = true,
                        IncludeSensitiveDataInLogs = true,
                        WebApiDiagnosticsIsVerbose = false
                    },
                    EventsOptions = new EventsOptions
                    {
                        RaiseSuccessEvents     = true,
                        RaiseErrorEvents       = true,
                        RaiseFailureEvents     = true,
                        RaiseInformationEvents = true
                    }
                };


                coreApp.UseIdentityServer(options);
            });

            app.Map("/core2", coreApp =>
            {
                var options = new IdentityServerOptions
                {
                    IssuerUri             = "https://" + serverName + "/identityserver",
                    SiteName              = "Identity Server Name",
                    SigningCertificate    = Cert.Load(serverName),
                    Factory               = factory,
                    CorsPolicy            = CorsPolicy.AllowAll,
                    RequireSsl            = true,
                    EnableWelcomePage     = false,
                    AuthenticationOptions = new AuthenticationOptions
                    {
                        EnableLoginHint                           = true,
                        EnableSignOutPrompt                       = false,
                        EnableLocalLogin                          = false,
                        EnablePostSignOutAutoRedirect             = true,
                        PostSignOutAutoRedirectDelay              = 0,
                        RequireAuthenticatedUserForSignOutMessage = false,
                        RememberLastUsername                      = false,
                        SignInMessageThreshold                    = 3,
                        IdentityProviders                         = ConfigureAdditionalIdentityProviders2,
                        CookieOptions = new Thinktecture.IdentityServer.Core.Configuration.CookieOptions()
                        {
                            Prefix     = "Core2",
                            SecureMode = CookieSecureMode.Always
                        }
                    },
                    LoggingOptions = new LoggingOptions
                    {
                        EnableHttpLogging          = true,
                        EnableWebApiDiagnostics    = true,
                        IncludeSensitiveDataInLogs = true
                    },
                    EventsOptions = new EventsOptions
                    {
                        RaiseSuccessEvents     = true,
                        RaiseErrorEvents       = true,
                        RaiseFailureEvents     = true,
                        RaiseInformationEvents = true
                    }
                };
                coreApp.UseIdentityServer(options);
            });
        }
Exemple #28
0
 public TokenRequestValidator(IdentityServerOptions options, IAuthorizationCodeStore authorizationCodes, IRefreshTokenStore refreshTokens, IUserService users, CustomGrantValidator customGrantValidator,
                              ICustomRequestValidator customRequestValidator, ScopeValidator scopeValidator, IEventService events)
     : this(options, authorizationCodes, refreshTokens, (IBasicUserService)users, customGrantValidator, customRequestValidator, scopeValidator, events)
 {
 }
Exemple #29
0
        public static TokenValidator CreateTokenValidator(IReferenceTokenStore store = null, IProfileService profile = null, IdentityServerOptions options = null)
        {
            if (options == null)
            {
                options = TestIdentityServerOptions.Create();
            }

            if (profile == null)
            {
                profile = new TestProfileService();
            }

            if (store == null)
            {
                store = CreateReferenceTokenStore();
            }

            var clients = CreateClientStore();
            var context = new MockHttpContextAccessor(options);
            var logger  = TestLogger.Create <TokenValidator>();

            var validator = new TokenValidator(
                clients: clients,
                referenceTokenStore: store,
                customValidator: new DefaultCustomTokenValidator(
                    profile: profile,
                    clients: clients,
                    logger: TestLogger.Create <DefaultCustomTokenValidator>()),
                keys: new DefaultKeyMaterialService(new[] { new DefaultValidationKeysStore(new[] { TestCert.LoadSigningCredentials().Key }) }),
                logger: logger,
                options: options,
                context: context);

            return(validator);
        }
        // todo: remove this in 3.0.0 as it will be unnecessary. it's only being maintained now for backwards compat with 2.0 APIs.
        public static IAppBuilder ConfigureIdentityServerIssuer(this IAppBuilder app, IdentityServerOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (options.IssuerUri.IsPresent())
            {
                options.DynamicallyCalculatedIssuerUri = options.IssuerUri;
            }
            else
            {
                Action <IOwinContext> op = ctx =>
                {
                    var uri = ctx.Environment.GetIdentityServerBaseUrl();
                    if (uri.EndsWith("/"))
                    {
                        uri = uri.Substring(0, uri.Length - 1);
                    }
                    options.DynamicallyCalculatedIssuerUri = uri;
                };

                app.Use(async(ctx, next) =>
                {
                    if (op != null)
                    {
                        var tmp = op;
                        op      = null;
                        tmp(ctx);
                    }

                    await next();
                });
            }

            return(app);
        }
 public EventServiceDecorator(IdentityServerOptions options, OwinEnvironmentService owinEnvironment, IEventService inner)
 {
     this.options = options;
     this.context = new OwinContext(owinEnvironment.Environment);
     this.inner   = inner;
 }
Exemple #32
0
        public static AuthorizeRequestValidator CreateAuthorizeRequestValidator(
            IdentityServerOptions options        = null,
            IIssuerNameService issuerNameService = null,
            IResourceStore resourceStore         = null,
            IClientStore clients    = null,
            IProfileService profile = null,
            ICustomAuthorizeRequestValidator customValidator = null,
            IRedirectUriValidator uriValidator               = null,
            IResourceValidator resourceValidator             = null,
            JwtRequestValidator jwtRequestValidator          = null,
            IJwtRequestUriHttpClient jwtRequestUriHttpClient = null)
        {
            if (options == null)
            {
                options = TestIdentityServerOptions.Create();
            }

            if (issuerNameService == null)
            {
                issuerNameService = new TestIssuerNameService(options.IssuerUri);
            }

            if (resourceStore == null)
            {
                resourceStore = new InMemoryResourcesStore(TestScopes.GetIdentity(), TestScopes.GetApis(), TestScopes.GetScopes());
            }

            if (clients == null)
            {
                clients = new InMemoryClientStore(TestClients.Get());
            }

            if (customValidator == null)
            {
                customValidator = new DefaultCustomAuthorizeRequestValidator();
            }

            if (uriValidator == null)
            {
                uriValidator = new StrictRedirectUriValidator();
            }

            if (resourceValidator == null)
            {
                resourceValidator = CreateResourceValidator(resourceStore);
            }

            if (jwtRequestValidator == null)
            {
                jwtRequestValidator = new JwtRequestValidator("https://identityserver", new LoggerFactory().CreateLogger <JwtRequestValidator>());
            }

            if (jwtRequestUriHttpClient == null)
            {
                jwtRequestUriHttpClient = new DefaultJwtRequestUriHttpClient(new HttpClient(new NetworkHandler(new Exception("no jwt request uri response configured"))), options, new LoggerFactory());
            }


            var userSession = new MockUserSession();

            return(new AuthorizeRequestValidator(
                       options,
                       issuerNameService,
                       clients,
                       customValidator,
                       uriValidator,
                       resourceValidator,
                       userSession,
                       jwtRequestValidator,
                       jwtRequestUriHttpClient,
                       TestLogger.Create <AuthorizeRequestValidator>()));
        }
Exemple #33
0
 public ClientConfigurationValidation()
 {
     _options   = new IdentityServerOptions();
     _validator = new DefaultClientConfigurationValidator(_options);
 }
Exemple #34
0
        public static IClientSecretValidator CreateClientSecretValidator(IClientStore clients = null, SecretParser parser = null, SecretValidator validator = null, IdentityServerOptions options = null)
        {
            options = options ?? TestIdentityServerOptions.Create();

            if (clients == null)
            {
                clients = new InMemoryClientStore(TestClients.Get());
            }

            if (parser == null)
            {
                var parsers = new List <ISecretParser>
                {
                    new BasicAuthenticationSecretParser(options, TestLogger.Create <BasicAuthenticationSecretParser>()),
                    new PostBodySecretParser(options, TestLogger.Create <PostBodySecretParser>())
                };

                parser = new SecretParser(parsers, TestLogger.Create <SecretParser>());
            }

            if (validator == null)
            {
                var validators = new List <ISecretValidator>
                {
                    new HashedSharedSecretValidator(TestLogger.Create <HashedSharedSecretValidator>()),
                    new PlainTextSharedSecretValidator(TestLogger.Create <PlainTextSharedSecretValidator>())
                };

                validator = new SecretValidator(new StubClock(), validators, TestLogger.Create <SecretValidator>());
            }

            return(new ClientSecretValidator(clients, parser, validator, new TestEventService(), TestLogger.Create <ClientSecretValidator>()));
        }
 public EndpointRouter(IEnumerable <Endpoint> endpoints, IdentityServerOptions options, ILogger <EndpointRouter> logger)
 {
     _endpoints = endpoints;
     _options   = options;
     _logger    = logger;
 }
Exemple #36
0
        public void Configuration(IAppBuilder app)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()                // change with your desired log level
                         .WriteTo.File(@"C:\temp\myPath.txt") // remember to assign proper writing privileges on the file
                         .CreateLogger();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.Map("/identity", idsrvApp =>
            {
                var options = new IdentityServerOptions
                {
                    SiteName           = "Security Token Server",
                    SigningCertificate = LoadCertificate(),
                    Factory            = IdSrvFactory.Configure("SecurityTokenServiceConfig")
                };

                idsrvApp.UseIdentityServer(options);
            });

            app.Map("/UserManagement", adminApp =>
            {
                adminApp.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                {
                    Authority    = "https://*****:*****@"https://localhost:44300/UserManagement/",
                    ResponseType = "id_token",
                    SignInAsAuthenticationType = "Cookies",
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        SecurityTokenValidated = n =>
                        {
                            return(AddClaims(n));
                        }
                    }
                });
                var factory = new IdentityManagerServiceFactory();
                factory.ConfigureIdentityManagerService("SecurityTokenServiceConfig");

                adminApp.UseIdentityManager(new IdentityManagerOptions()
                {
                    Factory = factory,
                    SecurityConfiguration = new HostSecurityConfiguration
                    {
                        HostAuthenticationType = "Cookies",
                        AdminRoleName          = "UserManagementAdmin"
                    }
                });
            });

            app.Map("/Admin", adminApp =>
            {
                adminApp.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                {
                    Authority    = "https://*****:*****@"https://localhost:44300/Admin/",
                    ResponseType = "id_token",
                    SignInAsAuthenticationType = "Cookies",
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        SecurityTokenValidated = n =>
                        {
                            return(AddClaims(n));
                        }
                    }
                });
                var factory = new IdentityAdminServiceFactory();
                factory.Configure();
                adminApp.UseIdentityAdmin(new IdentityAdminOptions
                {
                    Factory = factory,
                    AdminSecurityConfiguration = new AdminHostSecurityConfiguration
                    {
                        HostAuthenticationType = "Cookies",
                        AdminRoleName          = "ClientScopeManagementAdmin"
                    }
                });
            });
        }
Exemple #37
0
        public void Configuration(IAppBuilder appBuilder)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Trace(outputTemplate: "{Timestamp} [{Level}] ({Name}){NewLine} {Message}{NewLine}{Exception}")
                         .CreateLogger();

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
                LoginPath          = new PathString("/Home/Login")
            });

            appBuilder.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "oidc",
                Authority          = "https://localhost:44333",
                ClientId           = "idmgr_and_idadmin",
                RedirectUri        = "https://localhost:44333",
                ResponseType       = "id_token",
                UseTokenLifetime   = false,
                Scope = "openid idmgr idAdmin",
                SignInAsAuthenticationType = "Cookies",
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = n =>
                    {
                        n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        return(Task.FromResult(0));
                    },
                    RedirectToIdentityProvider = async n =>
                    {
                        if (n.ProtocolMessage.RequestType == Microsoft.IdentityModel.Protocols.OpenIdConnectRequestType.LogoutRequest)
                        {
                            var result = await n.OwinContext.Authentication.AuthenticateAsync("Cookies");
                            if (result != null)
                            {
                                var id_token = result.Identity.Claims.GetValue("id_token");
                                if (id_token != null)
                                {
                                    n.ProtocolMessage.IdTokenHint           = id_token;
                                    n.ProtocolMessage.PostLogoutRedirectUri = "https://localhost:44333";
                                }
                            }
                        }
                    }
                }
            });

            var connString = ConfigurationManager.ConnectionStrings["IdSvr3Config"].ConnectionString;

            // Identity admin
            appBuilder.Map("/adm", adminApp =>
            {
                var idAdminOptions = new IdentityAdminOptions
                {
                    Factory = ConfigIdentityServerAdmin.Factory.Configure(connString),
                    AdminSecurityConfiguration = new IdentityAdmin.Configuration.AdminHostSecurityConfiguration()
                    {
                        HostAuthenticationType = IdentityAdmin.Constants.CookieAuthenticationType,
                        AdminRoleName          = "IdentityServerAdmin",
                        NameClaimType          = "name",
                        RoleClaimType          = "role",
                    }
                };

                adminApp.UseIdentityAdmin(idAdminOptions);
            });

            //Identity manager
            appBuilder.Map("/idm", adminApp =>
            {
                var idManagerOptions = new IdentityManagerOptions
                {
                    Factory = ConfigIdentityManager.Factory.Configure(connString),
                    SecurityConfiguration = new HostSecurityConfiguration()
                    {
                        HostAuthenticationType = IdentityManager.Constants.CookieAuthenticationType,
                        AdminRoleName          = "IdentityManagerAdmin",
                        NameClaimType          = "name",
                        RoleClaimType          = "role",
                    }
                };

                adminApp.UseIdentityManager(idManagerOptions);
            });

            // Identity server
            appBuilder.Map("/ids", adminApp =>
            {
                var idsrvOptions = new IdentityServerOptions
                {
                    Factory            = ConfigIdentityServer.Factory.Configure(connString),
                    SigningCertificate = Certificate.Get(),
                    RequireSsl         = true
                };

                appBuilder.UseIdentityServer(idsrvOptions);
            });
        }
Exemple #38
0
 /// <summary>
 /// Creates the parser with options
 /// </summary>
 /// <param name="options">IdentityServer options</param>
 public PostBodySecretParser(IdentityServerOptions options, ILoggerFactory loggerFactory)
 {
     _logger  = loggerFactory.CreateLogger <PostBodySecretParser>();
     _options = options;
 }
 protected internal SessionCookie(IOwinContext ctx, IdentityServerOptions options)
 {
     this.context = ctx;
     this.identityServerOptions = options;
 }
Exemple #40
0
        public void Configuration(IAppBuilder app)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Trace()
                         .CreateLogger();

            app.Map("/IdSrv3", idSrv3App =>
            {
                var options = new IdentityServerOptions
                {
                    SiteName = "Embedded IdentityServer",

                    Factory = new IdentityServerServiceFactory()
                              .UseInMemoryScopes(StandardScopes.All)
                              .UseInMemoryClients(Clients.Get())
                              .UseInMemoryUsers(Users.Get()),

                    RequireSsl = false,

                    AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions
                    {
                        EnableAutoCallbackForFederatedSignout = true,
                        EnableSignOutPrompt = false
                    },

                    SigningCertificate =
                        new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\Sustainsys.Saml2.SampleIdentityServer3.pfx"),

                    LoggingOptions = new LoggingOptions
                    {
                        EnableKatanaLogging = true
                    }
                };

                options.AuthenticationOptions.IdentityProviders = ConfigureSaml2;

                idSrv3App.UseIdentityServer(options);
            });

            app.Use(async(ctx, next) =>
            {
                await next.Invoke();
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.Use(async(ctx, next) =>
            {
                await next.Invoke();
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority    = "http://localhost:4589/IdSrv3",
                ClientId     = "serverside",
                ClientSecret = "somesecret",
                RedirectUri  = "http://localhost:4589/",
                ResponseType = "code id_token",

                SignInAsAuthenticationType = "Cookies"
            });

            app.Use(async(ctx, next) =>
            {
                await next.Invoke();
            });

            app.Map("/ServerSide-Login", loginApp =>
            {
                loginApp.Use((ctx, next) =>
                {
                    ctx.Authentication.Challenge(
                        new AuthenticationProperties
                    {
                        RedirectUri = "http://localhost:4589/"
                    },
                        OpenIdConnectAuthenticationDefaults.AuthenticationType);
                    ctx.Response.StatusCode = 401;

                    return(Task.FromResult(0));
                });
            });

            app.Map("/ServerSide-Logout", logoutApp =>
            {
                logoutApp.Use((ctx, next) =>
                {
                    ctx.Authentication.SignOut();
                    ctx.Response.Redirect("/");

                    return(Task.FromResult(0));
                });
            });
        }
 public FormPostCredentialExtraction()
 {
     _options = new IdentityServerOptions();
     _parser  = new PostBodySecretParser(_options);
 }