public void Configuration(IAppBuilder appBuilder) { //AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject; //JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>(); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.LiterateConsole(outputTemplate: "{Timestamp} [{Level}] ({Name}){NewLine} {Message}{NewLine}{Exception}") .CreateLogger(); var factory = new IdentityServerServiceFactory() .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); // Register our custom user service factory.UserService = new Registration<IUserService>(new CustomInMemoryUserService(Users.Get())); var options = new IdentityServerOptions { SiteName = "Kroll Secure Token Service", IssuerUri = "https://kroll-sts-local", SigningCertificate = Certificate.Get(), Factory = factory, PluginConfiguration = ConfigurePlugins, AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions { EnablePostSignOutAutoRedirect = true, IdentityProviders = ConfigureIdentityProviders, EnableLocalLogin = false } }; appBuilder.UseIdentityServer(options); }
/// <summary> /// Configura o mecanismo de identitdade, de acordo com o as configurações do idFactory. /// </summary> /// <param name="app"></param> /// <param name="namerOrConnStr"></param> /// <param name="idFactory"></param> public void InitializeIdServer(IAppBuilder app, string namerOrConnStr, IdentityServerServiceFactory idFactory) { #region CONFIGURAÇÃO DO IDENTITY SERVER app.Map("/identity", id => { var options = new IdentityServerOptions { SiteName = "GAC ERP Identity Server", SigningCertificate = Certificado.Get(), Factory = idFactory, AuthenticationOptions = new AuthenticationOptions { LoginPageLinks = new LoginPageLink[] { new LoginPageLink{ Href = "/Account/ForgotPassword", Text = "Esqueceu sua senha?" } }, EnableSignOutPrompt = false, EnablePostSignOutAutoRedirect = true }, }; id.UseIdentityServer(options); }); #endregion }
public static IdentityServerServiceFactory Configure(ApplicationDbContext dbContext) { var efConfig = new EntityFrameworkServiceOptions { ConnectionString = dbContext.ConnectionStringName, }; // these two calls just pre-populate the test DB from the in-memory config //running with db.Clients.Any() ConfigureClients(Clients.Get(), efConfig); ConfigureScopes(Scopes.Get(), efConfig); var factory = new IdentityServerServiceFactory(); factory.RegisterConfigurationServices(efConfig); factory.RegisterOperationalServices(efConfig); var viewOptions = new DefaultViewServiceOptions(); viewOptions.Stylesheets.Add("/Content/Site.css"); factory.ConfigureDefaultViewService(viewOptions); factory.CorsPolicyService = new Registration<ICorsPolicyService>(new DefaultCorsPolicyService { AllowAll = true }); return factory; }
public void Configuration(IAppBuilder appBuilder) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace() .CreateLogger(); var factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); factory.ClaimsProvider = new Registration<IClaimsProvider, MyCustomClaimsProvider>(); factory.Register(new Registration<ICustomLogger, MyCustomDebugLogger>()); factory.CorsPolicyService = new Registration<ICorsPolicyService>(new DefaultCorsPolicyService { AllowAll = true }); var options = new IdentityServerOptions { SiteName = "IdentityServer3 - DependencyInjection", SigningCertificate = Certificate.Get(), Factory = factory, }; appBuilder.UseIdentityServer(options); }
public static IdentityServerServiceFactory Configure(string connString) { var efConfig = new EntityFrameworkServiceOptions { ConnectionString = connString, //Schema = "foo", //SynchronousReads = true }; var cleanup = new TokenCleanup(efConfig, 10); cleanup.Start(); // these two calls just pre-populate the test DB from the in-memory config ConfigureClients(Clients.Get(), efConfig); ConfigureScopes(Scopes.Get(), efConfig); var factory = new IdentityServerServiceFactory(); factory.RegisterConfigurationServices(efConfig); factory.RegisterOperationalServices(efConfig); //factory.ConfigureClientStoreCache(); //factory.ConfigureScopeStoreCache(); factory.UseInMemoryUsers(Users.Get()); return factory; }
public static AppBuilder Create() { AppBuilder app = new AppBuilder(); var factory = new IdentityServerServiceFactory() .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()) .UseInMemoryUsers(Users.Get()); factory.CustomGrantValidators.Add(new Registration<ICustomGrantValidator, CustomGrantValidator>()); factory.CustomGrantValidators.Add(new Registration<ICustomGrantValidator, CustomGrantValidator2>()); app.UseIdentityServer(new IdentityServerOptions { EventsOptions = new EventsOptions { RaiseErrorEvents = true, RaiseFailureEvents = true, RaiseInformationEvents = true, RaiseSuccessEvents = true }, IssuerUri = "https://idsrv3", SigningCertificate = TestCert.Load(), Factory = factory }); return app; }
public void Configuration(IAppBuilder app) { var users = new List<InMemoryUser> { new InMemoryUser { Subject = "E4A8B8DA-87F9-41CB-AA33-F79E621B3A56", Username = "******", Password = "******", Claims = new List<Claim> { new Claim("email", "*****@*****.**"), new Claim("role", "badmin") } } }; var factory = new IdentityServerServiceFactory() .UseInMemoryUsers(users) .UseInMemoryScopes(new List<Scope>()) .UseInMemoryClients(new List<Client>()); app.UseIdentityServer(new IdentityServerOptions { Factory = factory, SigningCertificate = Cert.LoadSigning(), PluginConfiguration = PluginConfiguration }); }
public static IdentityServerServiceFactory Configure(AppConfiguration config) { var factory = new IdentityServerServiceFactory(); var scopeStore = new InMemoryScopeStore(Scopes.Get()); factory.ScopeStore = new Registration<IScopeStore>(scopeStore); var clientStore = new InMemoryClientStore(Clients.Get(config)); factory.ClientStore = new Registration<IClientStore>(clientStore); var efConfig = new EntityFrameworkServiceOptions { ConnectionString = "Weee.DefaultConnection", Schema = "Identity" }; factory.RegisterOperationalServices(efConfig); var cleanup = new TokenCleanup(efConfig); cleanup.Start(); string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Weee.DefaultConnection"].ConnectionString; var auditSecurityEventService = new SecurityEventDatabaseAuditor(connectionString); SecurityEventService eventService = new SecurityEventService(auditSecurityEventService); factory.Register<ISecurityEventAuditor>(new Registration<ISecurityEventAuditor>(auditSecurityEventService)); factory.EventService = new Registration<IEventService>(eventService); return factory; }
public void Configuration(IAppBuilder app) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace() .CreateLogger(); app.Map("/core", coreApp => { var factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Config.Users.Get()) .UseInMemoryClients(Config.Clients.Get()) .UseInMemoryScopes(Config.Scopes.Get()); factory.ConfigureClientStoreCache(); factory.ConfigureScopeStoreCache(); factory.ConfigureUserServiceCache(); var idsrvOptions = new IdentityServerOptions { Factory = factory, SigningCertificate = Config.Cert.Load(), RequireSsl = false, Endpoints = new EndpointOptions { // replaced by the introspection endpoint in v2.2 EnableAccessTokenValidationEndpoint = false } }; coreApp.UseIdentityServer(idsrvOptions); }); }
public void Configuration(IAppBuilder app) { app.Map( "/core", coreApp => { var factory = new IdentityServerServiceFactory() .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); factory.Register(new Registration<IdentityDbContext>()); factory.Register(new Registration<UserStore<IdentityUser>>()); factory.Register(new Registration<UserManager<IdentityUser, string>> (x => new UserManager<IdentityUser>(x.Resolve<UserStore<IdentityUser>>()))); factory.UserService = new Registration<IUserService, AspNetIdentityUserService<IdentityUser, string>>(); coreApp.UseIdentityServer(new IdentityServerOptions { SiteName = "Standalone Identity Server", SigningCertificate = Cert.Load(), Factory = factory, RequireSsl = true }); }); }
public void Configuration(IAppBuilder appBuilder) { Log.Logger = new LoggerConfiguration() .WriteTo.Trace(outputTemplate: "{Timestamp} [{Level}] ({Name}){NewLine} {Message}{NewLine}{Exception}") .CreateLogger(); appBuilder.Map("/windows", ConfigureWindowsTokenProvider); var factory = new IdentityServerServiceFactory() .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); factory.UserService = new Registration<IUserService>(typeof(ExternalRegistrationUserService)); var options = new IdentityServerOptions { SigningCertificate = Certificate.Load(), Factory = factory, AuthenticationOptions = new AuthenticationOptions { EnableLocalLogin = false, IdentityProviders = ConfigureIdentityProviders } }; appBuilder.UseIdentityServer(options); }
public void Configuration(IAppBuilder app) { // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888 app.Map("/identity", idsrvApp => { var idServerServiceFactory = new IdentityServerServiceFactory() .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()) .UseInMemoryUsers(Users.Get()); var options = new IdentityServerOptions { Factory = idServerServiceFactory, SiteName = "TripCompany Security Token service", IssuerUri = TripGallery.Constants.TripGalleryIssuerUri, PublicOrigin = TripGallery.Constants.TripGallerySTSOrigin , SigningCertificate = LoadCertificate() }; idsrvApp.UseIdentityServer(options); } ); }
public static IdentityServerServiceFactory Configure() { var factory = new IdentityServerServiceFactory(); var scopeStore = new InMemoryScopeStore(Scopes.Get()); factory.ScopeStore = new Registration<IScopeStore>(scopeStore); var clientStore = new InMemoryClientStore(Clients.Get()); factory.ClientStore = new Registration<IClientStore>(clientStore); factory.ConfigureUserService(); factory.CorsPolicyService = new Registration<ICorsPolicyService>(new DefaultCorsPolicyService { AllowAll = true }); var localizationService = new PortugueseBrazilLocalizationService(); factory.LocalizationService = new Registration<ILocalizationService>(localizationService); factory.ViewService = new Registration<IViewService, MvcViewService<LogonWorkflowController>>(); factory.Register(new Registration<HttpContext>(resolver => HttpContext.Current)); factory.Register(new Registration<HttpContextBase>(resolver => new HttpContextWrapper(resolver.Resolve<HttpContext>()))); factory.Register(new Registration<HttpRequestBase>(resolver => resolver.Resolve<HttpContextBase>().Request)); factory.Register(new Registration<HttpResponseBase>(resolver => resolver.Resolve<HttpContextBase>().Response)); factory.Register(new Registration<HttpServerUtilityBase>(resolver => resolver.Resolve<HttpContextBase>().Server)); factory.Register(new Registration<HttpSessionStateBase>(resolver => resolver.Resolve<HttpContextBase>().Session)); return factory; }
public static IdentityServerServiceFactory Configure(string connString) { var efConfig = new EntityFrameworkServiceOptions { ConnectionString = connString, }; // these two calls just pre-populate the test DB from the in-memory config ConfigureClients(Clients.Get(), efConfig); ConfigureScopes(Scopes.Get(), efConfig); var factory = new IdentityServerServiceFactory(); factory.RegisterConfigurationServices(efConfig); factory.RegisterOperationalServices(efConfig); //var scopeStore = new InMemoryScopeStore(Scopes.Get()); //factory.ScopeStore = new Registration<IScopeStore>(scopeStore); //var clientStore = new InMemoryClientStore(Clients.Get()); //factory.ClientStore = new Registration<IClientStore>(clientStore); factory.ConfigureUserService(connString); factory.CorsPolicyService = new Registration<ICorsPolicyService>(new DefaultCorsPolicyService { AllowAll = true }); return factory; }
public static IdentityServerServiceFactory Configure(string connString) { var efConfig = new EntityFrameworkServiceOptions { ConnectionString = connString, }; // these two calls just pre-populate the test DB from the in-memory config ConfigureClients(DefaultClients.Get(), efConfig); ConfigureScopes(DefaultScopes.Get(), efConfig); // ------------------------------------------------ var factory = new IdentityServerServiceFactory(); factory.RegisterConfigurationServices(efConfig); factory.RegisterOperationalServices(efConfig); // ----- MembershipReboot user service (pripajanie na ulozisko identit) factory.UserService = new Registration<IUserService, CustomUserService>(); factory.Register(new Registration<CustomUserAccountService>()); factory.Register(new Registration<CustomConfig>(CustomConfig.Config)); factory.Register(new Registration<CustomUserRepository>()); factory.Register(new Registration<CustomDatabase>(resolver => new CustomDatabase(connString))); return factory; }
public void Configuration(IAppBuilder app) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace() .CreateLogger(); app.Map("/core", coreApp => { var factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); factory.ViewService = new Registration<IViewService, CustomViewService>(); // this custom user service shows how to accept custom form params on login page //factory.UserService = new Registration<IUserService, UserService>(); var options = new IdentityServerOptions { SiteName = "IdentityServer33 - CustomViewService", SigningCertificate = Certificate.Get(), Factory = factory, AuthenticationOptions = new AuthenticationOptions { IdentityProviders = ConfigureAdditionalIdentityProviders, } }; coreApp.UseIdentityServer(options); }); }
public void Configuration(IAppBuilder app) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace() .CreateLogger(); app.Map("/core", coreApp => { var factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); var viewOptions = new DefaultViewServiceOptions(); viewOptions.Stylesheets.Add("/Content/Site.css"); viewOptions.CacheViews = false; factory.ConfigureDefaultViewService(viewOptions); var options = new IdentityServerOptions { SiteName = "IdentityServer3 - Configuring DefaultViewService", SigningCertificate = Certificate.Get(), Factory = factory, AuthenticationOptions = new AuthenticationOptions{ IdentityProviders = ConfigureAdditionalIdentityProviders, } }; coreApp.UseIdentityServer(options); }); }
public void Configuration(IAppBuilder app) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace() .CreateLogger(); app.Map("/core", coreApp => { var factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); factory.ViewService = new Registration<IViewService>(typeof(CustomViewService)); //factory.UserService = new Registration<IUserService, UserService>(); factory.CorsPolicyService = new Registration<ICorsPolicyService>(new DefaultCorsPolicyService { AllowAll = true }); var options = new IdentityServerOptions { SiteName = "IdentityServer33 - CustomViewService", SigningCertificate = Certificate.Get(), Factory = factory, AuthenticationOptions = new AuthenticationOptions { IdentityProviders = ConfigureAdditionalIdentityProviders, } }; coreApp.UseIdentityServer(options); }); }
public static IAppBuilder UseIdentityServer(this IAppBuilder app) { // uncomment to enable HSTS headers for the host // see: https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security //app.UseHsts(); app.Map("/core", coreApp => { var factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); factory.CustomGrantValidators.Add( new Registration<ICustomGrantValidator>(typeof(CustomGrantValidator))); factory.CustomGrantValidators.Add( new Registration<ICustomGrantValidator>(typeof(AnotherCustomGrantValidator))); factory.ConfigureClientStoreCache(); factory.ConfigureScopeStoreCache(); factory.ConfigureUserServiceCache(); factory.TokenSigningService = new Registration<ITokenSigningService, EnhancedDefaultTokenSigningService>(); var idsrvOptions = new IdentityServerOptions { Factory = factory, SigningCertificate = Cert.Load(), Endpoints = new EndpointOptions { // replaced by the introspection endpoint in v2.2 EnableAccessTokenValidationEndpoint = false }, AuthenticationOptions = new AuthenticationOptions { IdentityProviders = ConfigureIdentityProviders, //EnablePostSignOutAutoRedirect = true }, //LoggingOptions = new LoggingOptions //{ // EnableKatanaLogging = true //}, //EventsOptions = new EventsOptions //{ // RaiseFailureEvents = true, // RaiseInformationEvents = true, // RaiseSuccessEvents = true, // RaiseErrorEvents = true //} }; coreApp.UseIdentityServer(idsrvOptions); }); return app; }
public void Configuration(IAppBuilder app) { // tracing Log.Logger = new LoggerConfiguration() .WriteTo.Trace() .CreateLogger(); // in-memory datenhaltung für users, scopes, clients und CORS policys var users = new InMemoryUserService(Users.Get()); var scopes = new InMemoryScopeStore(Scopes.Get()); var clients = new InMemoryClientStore(Clients.Get()); var cors = new InMemoryCorsPolicyService(Clients.Get()); // konfigurieren der factory var factory = new IdentityServerServiceFactory(); factory.UserService = new Registration<IUserService>(users); factory.ScopeStore = new Registration<IScopeStore>(scopes); factory.ClientStore = new Registration<IClientStore>(clients); factory.CorsPolicyService = new Registration<ICorsPolicyService>(cors); // identityserver3 middleware einbinden app.UseIdentityServer(new IdentityServerOptions { Factory = factory, SiteName = "DotNetPro IdentityServer", SigningCertificate = Certificate.Get() }); }
public void Configuration(IAppBuilder app) { // setup serilog to use diagnostics trace Log.Logger = new LoggerConfiguration() .WriteTo.Trace(outputTemplate: "{Timestamp} [{Level}] ({Name}){NewLine} {Message}{NewLine}{Exception}") .CreateLogger(); app.Map("/core", coreApp => { var factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); var options = new IdentityServerOptions { SiteName = "IdentityServer3 with WS-Federation", SigningCertificate = Certificate.Get(), Factory = factory, PluginConfiguration = ConfigurePlugins, }; coreApp.UseIdentityServer(options); }); }
public void Configuration(IAppBuilder appBuilder) { var factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryScopes(Scopes.Get()) .UseInMemoryClients(Clients.Get()); factory.ClaimsProvider = new Registration<IClaimsProvider>(typeof(CustomClaimsProvider)); factory.UserService = new Registration<IUserService>(typeof(CustomUserService)); factory.CustomGrantValidators.Add( new Registration<ICustomGrantValidator>(typeof(CustomGrantValidator))); var options = new IdentityServerOptions { SiteName = "IdentityServer3 (CustomGrants)", RequireSsl = false, SigningCertificate = Certificate.Get(), Factory = factory, }; appBuilder.UseIdentityServer(options); }
public void Configuration(IAppBuilder appBuilder) { var factory = new IdentityServerServiceFactory() .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()) .UseInMemoryUsers(Users.Get()); factory.EventService = new Registration<IEventService, SeqEventService>(); var options = new IdentityServerOptions { SiteName = "IdentityServer3 (self host)", SigningCertificate = Certificate.Get(), Factory = factory, EventsOptions = new EventsOptions { RaiseErrorEvents = true, RaiseFailureEvents = true, RaiseInformationEvents = true, RaiseSuccessEvents = true } }; appBuilder.UseIdentityServer(options); }
public void Configuration(IAppBuilder appBuilder) { Log.Logger = new LoggerConfiguration() .WriteTo.Trace(outputTemplate: "{Timestamp} [{Level}] ({Name}){NewLine} {Message}{NewLine}{Exception}") .CreateLogger(); var factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); // Use the Mvc View Service instead of the default factory.ViewService = new Registration<IViewService, MvcViewService<LogonWorkflowController>>(); // These registrations are also needed since these are dealt with using non-standard construction factory.Register(new Registration<HttpContext>(resolver => HttpContext.Current)); factory.Register(new Registration<HttpContextBase>(resolver => new HttpContextWrapper(resolver.Resolve<HttpContext>()))); factory.Register(new Registration<HttpRequestBase>(resolver => resolver.Resolve<HttpContextBase>().Request)); factory.Register(new Registration<HttpResponseBase>(resolver => resolver.Resolve<HttpContextBase>().Response)); factory.Register(new Registration<HttpServerUtilityBase>(resolver => resolver.Resolve<HttpContextBase>().Server)); factory.Register(new Registration<HttpSessionStateBase>(resolver => resolver.Resolve<HttpContextBase>().Session)); var options = new IdentityServerOptions { SigningCertificate = Certificate.Load(), Factory = factory }; appBuilder.Map("/core", idsrvApp => { idsrvApp.UseIdentityServer(options); }); }
public void Configuration(IAppBuilder app) { // setup serilog to use diagnostics trace Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace() .CreateLogger(); // uncomment to enable HSTS headers for the host // see: https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security //app.UseHsts(); app.Map("/core", coreApp => { var factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); factory.CustomGrantValidators.Add( new Registration<ICustomGrantValidator>(typeof(CustomGrantValidator))); factory.CustomGrantValidators.Add( new Registration<ICustomGrantValidator>(typeof(AnotherCustomGrantValidator))); factory.ConfigureClientStoreCache(); factory.ConfigureScopeStoreCache(); factory.ConfigureUserServiceCache(); var idsrvOptions = new IdentityServerOptions { Factory = factory, SigningCertificate = Cert.Load(), AuthenticationOptions = new AuthenticationOptions { IdentityProviders = ConfigureIdentityProviders, //EnablePostSignOutAutoRedirect = true }, LoggingOptions = new LoggingOptions { EnableKatanaLogging = true }, EventsOptions = new EventsOptions { RaiseFailureEvents = true, RaiseInformationEvents = true, RaiseSuccessEvents = true, RaiseErrorEvents = true } }; coreApp.UseIdentityServer(idsrvOptions); }); }
public IdentityServerOptions GetServerOptions() { var factory = new IdentityServerServiceFactory(); var knownClientStore = new KnownClientStore(identityManagerUri, identityAdminUri); factory.ClientStore = new Registration<IClientStore>( new CompositeClientStore(new IClientStore[] { new ClientStore(new ClientConfigurationDbContext("ClientsScopes")), // TODO: get connection string name from config knownClientStore })); factory.ScopeStore = new Registration<IScopeStore>( new CompositeScopeStore(new IScopeStore[] { new ScopeStore(new ScopeConfigurationDbContext("ClientsScopes")), // TODO: get connection string name from config new KnownScopeStore() })); factory.UserService = new Registration<IUserService>( new CompositeUserService(new IUserService[] { new ClaimsUserService(new NullClaimsService(), userService), new KnownUserService(this.adminUsername, this.adminPassword) })); factory.CorsPolicyService = new Registration<ICorsPolicyService>( new CompositeCorsPolicyService(new ICorsPolicyService[] { new ClientConfigurationCorsPolicyService(new ClientConfigurationDbContext("ClientsScopes")), // TODO: get connection string name from config new InMemoryCorsPolicyService(knownClientStore.GetClients()) })); //We can choose how to display the login screen LoadViewService(factory); return new IdentityServerOptions { SiteName = "IdentityServer v3", SigningCertificate = Cert.Load(typeof(IOwinBootstrapper).Assembly, "Cert", "idsrv3test.pfx", "idsrv3test"), Endpoints = new EndpointOptions { EnableCspReportEndpoint = true }, AuthenticationOptions = new AuthenticationOptions { IdentityProviders = externalIdentityProviderService.UseExternalIdentityProviders, //Registration link on login page LoginPageLinks = new LoginPageLink[] { new LoginPageLink { Text = "Register", Href= "localregistration"} } }, Factory = factory }; }
public void Configuration(IAppBuilder app) { // config identity server var factory = new IdentityServerServiceFactory { CorsPolicyService = new IdentityServer3.Core.Configuration.Registration<ICorsPolicyService>(new DefaultCorsPolicyService {AllowAll = true}), ScopeStore = new IdentityServer3.Core.Configuration.Registration<IScopeStore>(new InMemoryScopeStore(Scopes.Get())), ClientStore = new IdentityServer3.Core.Configuration.Registration<IClientStore>(new InMemoryClientStore(Clients.Get())) }; factory.ConfigureUserService(ConnectionString); app.Map("/identity", idServer => idServer.UseIdentityServer(new IdentityServerOptions { SiteName = "Identity Server for 8sApp", RequireSsl = false, Factory = factory, SigningCertificate = Certificate.Certificate.Get(), AuthenticationOptions = new AuthenticationOptions() { LoginPageLinks = new[] { new LoginPageLink { Text = "Register", Href = "register" } } } })); // config identity manager app.Map("/admin", adminApp => { var identityManagerServiceFactory = new IdentityManagerServiceFactory(); identityManagerServiceFactory.ConfigureIdentityManagerService(ConnectionString); var options = new IdentityManagerOptions { Factory = identityManagerServiceFactory, SecurityConfiguration = {RequireSsl = false} }; adminApp.UseIdentityManager(options); }); // config web api var config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); app.UseCors(CorsOptions.AllowAll); app.UseWebApi(config); }
public static IdentityServerServiceFactory Configure() { var factory = new IdentityServerServiceFactory(); factory .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()) .UseInMemoryUsers(Users.Get()); factory.CorsPolicyService = new Registration<ICorsPolicyService>(new DefaultCorsPolicyService { AllowAll = true }); return factory; }
public void Configuration(IAppBuilder app) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace() .CreateLogger(); app.Map("/core", coreApp => { var factory = new IdentityServerServiceFactory() .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); // different examples of custom user services //var userService = new RegisterFirstExternalRegistrationUserService(); //var userService = new ExternalRegistrationUserService(); var userService = new EulaAtLoginUserService(); //var userService = new LocalRegistrationUserService(); // 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 { IdentityProviders = ConfigureAdditionalIdentityProviders, LoginPageLinks = new LoginPageLink[] { new LoginPageLink{ Text = "Register", //Href = "~/localregistration" Href = "localregistration" } } }, EventsOptions = new EventsOptions { RaiseSuccessEvents = true, RaiseErrorEvents = true, RaiseFailureEvents = true, RaiseInformationEvents = true } }; coreApp.UseIdentityServer(options); }); }
public static IdentityServerServiceFactory Configure() { var factory = new IdentityServerServiceFactory(); var scopeStore = new InMemoryScopeStore(Scopes.Get()); factory.ScopeStore = new Registration<IScopeStore>(resolver => scopeStore); var clientStore = new InMemoryClientStore(Clients.Get()); factory.ClientStore = new Registration<IClientStore>(resolver => clientStore); return factory; }
public void Configuration(IAppBuilder app) { // enable CORS var corsPolicyService = new DefaultCorsPolicyService() { AllowAll = true }; /*Now let's ensure we startup identity server with the correct configuration so it uses what we just added. */ /*Here we are mapping to a certain URI\identity with app.map we can map that \identity URI to the identity server app and configure it. To startup identity server, we can use a factor and pass that into the options used for configuring identity server. When configuring this factory, we can state where the clients, scopes, and users come from. */ app.Map("/identity", idsrvApp => { // here we are configuring a security token service (STS) var idServerServiceFactory = new IdentityServerServiceFactory() .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); //.UseInMemoryUsers(Users.Get()); // we can now start using our CustomUserService(). // do not cache the views var defaultViewServiceOptions = new DefaultViewServiceOptions(); defaultViewServiceOptions.CacheViews = false; // Register CORS idServerServiceFactory.CorsPolicyService = new Registration <IdentityServer3.Core.Services.ICorsPolicyService>(corsPolicyService); // use our custom UserService var customUserService = new CustomUserService(); idServerServiceFactory.UserService = new Registration <IUserService>(resolver => customUserService); // create an identityserver option instance var options = new IdentityServerOptions { Factory = idServerServiceFactory, SiteName = "TripCompany Security Token Service", IssuerUri = TripGallery.Constants.TripGalleryIssuerUri, PublicOrigin = TripGallery.Constants.TripGallerySTSOrigin, SigningCertificate = LoadCertificate(), AuthenticationOptions = new AuthenticationOptions() { EnablePostSignOutAutoRedirect = true, //enable single-sign-out //PostSignOutAutoRedirectDelay = 2 // 2 seconds delay LoginPageLinks = new List <LoginPageLink>() // link for registration { new LoginPageLink() { Type = "createaccount", Text = "Create a new account", Href = "~/createuseraccount" } }, IdentityProviders = ConfigureAdditionalIdProviders }, CspOptions = new CspOptions() { Enabled = false // once available, leave Enabled at true and use: // FrameSrc = "https://localhost:44318 https://localhost:44316" // or // FrameSrc = "*" for all URI's. } }; idsrvApp.UseIdentityServer(options); }); }
public static void ConfigureScope(this IdentityServerServiceFactory factory, RavenServiceOptions options) { options.Store.Conventions.RegisterIdConvention <Scope>( (dbname, commands, scope) => options.Store.Conventions.FindTypeTagName(typeof(Scope)) + "/" + scope.Name); factory.Register(new Registration <IScopeStore, ScopeStore>()); }
public static void ConfigureRavenSession(this IdentityServerServiceFactory factory, RavenServiceOptions options) { IndexCreation.CreateIndexes(typeof(RavenServiceOptions).Assembly, options.Store); factory.Register(new Registration <IAsyncDocumentSession>(resolver => options.Store.OpenAsyncSession(options.DatabaseName))); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context, user manager and signin manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie 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)) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); app.Map("/auth", auth => { var idserverFactory = new IdentityServerServiceFactory() .UseInMemoryClients(GetClient()) .UseInMemoryScopes(GetScopes()); idserverFactory.UserService = new Registration <IUserService, IdentityServer3.AspNetIdentity.AspNetIdentityUserService <ApplicationUser, string> >(); idserverFactory.Register(new Registration <UserManager <ApplicationUser, string>, ApplicationUserManager>()); idserverFactory.Register(new Registration <IUserStore <ApplicationUser> >(resolver => new UserStore <ApplicationUser>(resolver.Resolve <ApplicationDbContext>()))); idserverFactory.Register(new Registration <ApplicationDbContext, ApplicationDbContext>()); var options = new IdentityServerOptions { SiteName = "WebSiteWithSecuriteez", SigningCertificate = Certificate.Load(), RequireSsl = false, Factory = idserverFactory, AuthenticationOptions = new AuthenticationOptions() }; auth.UseIdentityServer(options); }); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. //app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. //app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); }
public static void RegisterAsAutofacResolvable <T>(this IdentityServerServiceFactory factory, RegistrationContext context, Func <ILifetimeScope, T> resolveWithLifetimeScopeFunc = null, Func <IOwinContext, T> resolveWithOwinContextFunc = null, string name = null) where T : class { factory.Register(CreateRegistration(context, resolveWithLifetimeScopeFunc, resolveWithOwinContextFunc, name)); }
public void Configuration(IAppBuilder appBuilder) { var connectionString = ConfigurationManager.AppSettings["Connection"]; JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>(); appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); appBuilder.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); appBuilder.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { AuthenticationType = "oidc", Authority = ConfigurationManager.AppSettings["IdentityServer"], ClientId = "idmgr_client", RedirectUri = ConfigurationManager.AppSettings["IdentityManager"], ResponseType = "id_token", UseTokenLifetime = false, Scope = "openid idmgr", SignInAsAuthenticationType = "Cookies" }); // Identity Manager appBuilder.Map("/admin", adminApp => { var factory = new IdentityManagerServiceFactory(); factory.Configure(connectionString); var options = new IdentityManagerOptions { Factory = factory }; if (Convert.ToBoolean(ConfigurationManager.AppSettings["SecurityEnabled"])) { options.SecurityConfiguration = new HostSecurityConfiguration { HostAuthenticationType = "Cookies", AdditionalSignOutType = "oidc" }; } adminApp.UseIdentityManager(options); }); // Identity Server var idFactory = new IdentityServerServiceFactory(); idFactory.Configure(connectionString); var idOptions = new IdentityServerOptions { SigningCertificate = Certificate.Load(), Factory = idFactory, CorsPolicy = CorsPolicy.AllowAll, AuthenticationOptions = new AuthenticationOptions { IdentityProviders = ConfigureIdentityProviders } }; appBuilder.UseIdentityServer(idOptions); }
public void Configuration(IAppBuilder app) { AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject; JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>(); var factory = new IdentityServerServiceFactory() // .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); // factory.UserService = new Registration<IUserService>(context => new UserService(Users.Get())); factory.Register(new Registration <List <InMemoryUser> >(Users.Get())); factory.UserService = new Registration <IUserService, UserService>(); var identityServerOptions = new IdentityServerOptions { // RequireSsl = false, SiteName = "Embedded IdentityServer", SigningCertificate = Certificate.Get(), Factory = factory, AuthenticationOptions = new AuthenticationOptions { // EnableLocalLogin = false, EnablePostSignOutAutoRedirect = true, IdentityProviders = this.ConfigureIdentityProviders } }; app.Map("/identity", idsrvApp => { idsrvApp.UseIdentityServer(identityServerOptions); }); app.UseResourceAuthorization(new AuthorizationManager()); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { Authority = "https://localhost:44319/identity", ClientId = "mvc", Scope = "openid profile roles", RedirectUri = "https://localhost:44319/", ResponseType = "id_token", SignInAsAuthenticationType = "Cookies", UseTokenLifetime = false, Notifications = new OpenIdConnectAuthenticationNotifications { SecurityTokenValidated = n => { var id = n.AuthenticationTicket.Identity; // we want to keep first name, last name, subject and roles var givenName = id.FindFirst(Constants.ClaimTypes.GivenName); var familyName = id.FindFirst(Constants.ClaimTypes.FamilyName); var sub = id.FindFirst(Constants.ClaimTypes.Subject); var roles = id.FindAll(Constants.ClaimTypes.Role); // create new identity and set name and role claim type var nid = new ClaimsIdentity( id.AuthenticationType, Constants.ClaimTypes.GivenName, Constants.ClaimTypes.Role); //nid.AddClaim(givenName); //nid.AddClaim(familyName); //nid.AddClaim(sub); //nid.AddClaims(roles); // add some other app specific claim nid.AddClaim(new Claim("app_specific", "some data")); nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); //n.AuthenticationTicket = new AuthenticationTicket( // nid, // n.AuthenticationTicket.Properties); return(Task.FromResult(0)); }, RedirectToIdentityProvider = n => { if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) { var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token"); if (idTokenHint != null) { n.ProtocolMessage.IdTokenHint = idTokenHint.Value; } } return(Task.FromResult(0)); } } }); }
public void Configuration(IAppBuilder app) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.ColoredConsole() .CreateLogger(); // ## Users (In Memory) var users = new List <InMemoryUser> { // Customer - Bob new InMemoryUser { Username = "******", Password = "******", Subject = "1", // A special claim that is unique to that customer, it should never change Claims = new List <Claim> { new Claim("name", "Bob Smith"), new Claim("email", "*****@*****.**"), new Claim("role", "customer") }, }, // Administrator - Juan Carlos new InMemoryUser { Username = "******", Password = "******", Subject = "0", // A special claim that is unique to that customer, it should never change Claims = new List <Claim> { new Claim("name", "Juan Carlos"), new Claim("gender", "male"), new Claim("nickname", "juasan00"), new Claim("email", "*****@*****.**"), new Claim("role", "admin") }, } }; // ## Scopes (Claims): There are two types: Identity Scopes and Resources Scopes (WebApis) var scopes = new List <Scope> { // Standard Claims StandardScopes.OpenId, StandardScopes.Profile, StandardScopes.Email, StandardScopes.OfflineAccess, // This allows refresh tokens: https://identityserver.github.io/Documentation/docsv2/advanced/refreshTokens.html // Custom Claims // Identity: Role new Scope { Name = "role", DisplayName = "Role", Description = "Your role", Type = ScopeType.Identity, Claims = new List <ScopeClaim> { new ScopeClaim("role") } }, // Resource API new Scope { Name = "tickets_api", DisplayName = "Tickets api", Description = "This is an API to get and create tickets", Type = ScopeType.Resource, } }; // ## Clients = registered applications var clients = new List <Client> { new Client { ClientId = "mvc", ClientName = "MVC Demo", ClientSecrets = new List <Secret> { new Secret("secret".Sha256()) }, //RequireConsent = false, // consent makes sense only for 3rd party apps Flow = Flows.Hybrid, // Flow supported by UseOpenIdConnectAuthentication (code + implicit) RedirectUris = new List <string> { // Where to redirect the call, the MVC address "https://localhost:44333" + "/signin-oidc" // default Microsoft openId middle ware callback path }, PostLogoutRedirectUris = new List <string> { "https://localhost:44333" }, AllowedScopes = new List <string> { // Information that the application can access, StandardScopes.OpenId.Name, StandardScopes.Email.Name, StandardScopes.Profile.Name, StandardScopes.OfflineAccess.Name, "role", "tickets_api" }, } }; var factory = new IdentityServerServiceFactory(); factory.UseInMemoryClients(clients); factory.UseInMemoryScopes(scopes); factory.UseInMemoryUsers(users); app.UseIdentityServer(new IdentityServerOptions { SiteName = "Identity Server Demo", SigningCertificate = SigningCertificate.Load(), // certificate used to sign in issued tokens Factory = factory // factory to find all users and resources }); app.Run(async context => { await context.Response.WriteAsync("Path not found: " + context.Request.Path); }); }
public void Configuration(IAppBuilder app) { ConfigureAuth(app); var path = HostingEnvironment.MapPath("~/App_Data"); var userService = new Registration <IUserService>(new UserServiceBase()); var inMemoryFactory = new IdentityServerServiceFactory() .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()) .UseInMemoryUsers(Users.Get()); // Create and modify default settings StoreSettings settings = StoreSettings.DefaultSettings; settings.Folder = path; ClientStore myClientStore = new ClientStore(settings); foreach (var client in Clients.Get()) { myClientStore.CreateAsync(new ClientHandle(client)); } ScopeStore myScopeStore = new ScopeStore(settings); foreach (var scope in Scopes.Get()) { myScopeStore.CreateAsync(new ScopeHandle(scope)); } // Create the BiggyIdentityService factory var factory = new ServiceFactory(userService, settings); factory.UseInMemoryUsers(Users.Get()); factory.CustomGrantValidators.Add( new Registration <ICustomGrantValidator>(typeof(CustomGrantValidator))); factory.CustomGrantValidators.Add( new Registration <ICustomGrantValidator>(typeof(ActAsGrantValidator))); factory.ClaimsProvider = new Registration <IClaimsProvider>(typeof(CustomClaimsProvider)); var options = new IdentityServerOptions { Factory = factory, RequireSsl = false, // SigningCertificate = Certificate.Get(), SiteName = "P5 IdentityServer3" }; app.Map("/idsrv3core", idsrvApp => { idsrvApp.UseIdentityServer(options); }); app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions { Authority = "http://localhost:33854/idsrv3core", ValidationMode = ValidationMode.ValidationEndpoint, RequiredScopes = new[] { "CustomWebApi1", "api1", "WebApi1", "WebApi2", "read" }, PreserveAccessToken = true }); HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); app.UseWebApi(config); }
/// <summary> /// Initializes a new instance of the <see cref="PluginServiceFactory"/> class. /// </summary> /// <param name="factory">The factory.</param> public PluginServiceFactory(IdentityServerServiceFactory factory) { UserService = factory.UserService; }
public static void RegisterConfigurationServices(this IdentityServerServiceFactory factory, EntityFrameworkServiceOptions options) { IdentityServerServiceFactoryExtensions.RegisterClientStore(factory, options); IdentityServerServiceFactoryExtensions.RegisterScopeStore(factory, options); }
public void Configuration(IAppBuilder app) { // todo: replace with serilog //LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider()); AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject; JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>(); app.Map("/identity", idsrvApp => { var factory = new IdentityServerServiceFactory() .UseInMemoryUsers(Users.Get()) .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); var viewOptions = new DefaultViewServiceOptions(); viewOptions.Stylesheets.Add("~/Content/Site.css"); viewOptions.Stylesheets.Add("~/Content/animation-style_css"); viewOptions.CacheViews = false; factory.ConfigureDefaultViewService(viewOptions); var options = new IdentityServerOptions { SiteName = "PRIS", SigningCertificate = LoadCertificate(), Factory = factory, RequireSsl = false, AuthenticationOptions = new AuthenticationOptions { IdentityProviders = ConfigureAdditionalIdentityProviders, } }; idsrvApp.UseIdentityServer(options); }); app.UseResourceAuthorization(new AuthorizationManager()); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" }); #region openIdConnect //app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions //{ // Authority = "https://localhost:44319/identity", // ClientId = "mvc", // Scope = "openid profile roles sampleApi", // ResponseType = "id_token token", // RedirectUri = "https://localhost:44319/", // SignInAsAuthenticationType = "Cookies", // UseTokenLifetime = false, // Notifications = new OpenIdConnectAuthenticationNotifications // { // SecurityTokenValidated = async n => // { // var nid = new ClaimsIdentity( // n.AuthenticationTicket.Identity.AuthenticationType, // Constants.ClaimTypes.GivenName, // Constants.ClaimTypes.Role); // // get userinfo data // var userInfoClient = new UserInfoClient( // new Uri(n.Options.Authority + "/connect/userinfo"), // n.ProtocolMessage.AccessToken); // var userInfo = await userInfoClient.GetAsync(); // userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2))); // // keep the id_token for logout // nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); // // add access token for sample API // nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken)); // // keep track of access token expiration // nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString())); // // add some other app specific claim // nid.AddClaim(new Claim("app_specific", "some data")); // n.AuthenticationTicket = new AuthenticationTicket( // nid, // n.AuthenticationTicket.Properties); // }, // RedirectToIdentityProvider = n => // { // if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) // { // var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token"); // if (idTokenHint != null) // { // n.ProtocolMessage.IdTokenHint = idTokenHint.Value; // } // } // return Task.FromResult(0); // } // } //}); #endregion }
public void Configuration(IAppBuilder app) { var kernel = WebSetup.SetupDependencyInjection(RegisterServices, ConfigurationManager.AppSettings); var config = kernel.Get <IConfigService>(); var log = kernel.Get <ILogger>(); var userService = kernel.Get <SarUserService>(); var clientStore = kernel.Get <IClientStore>(); var corsService = new DefaultCorsPolicyService { AllowAll = true }; var factory = new IdentityServerServiceFactory { UserService = new Registration <IUserService>(resolver => userService), ClientStore = new Registration <IClientStore>(resolver => clientStore), CorsPolicyService = new Registration <ICorsPolicyService>(resolver => corsService), ViewService = new Registration <IViewService, MvcViewService <AccountController> >(), TokenSigningService = new Registration <ITokenSigningService, MyTokenSigningService>() } .UseInMemoryScopes(Scopes.Get(kernel.Get <Func <IAuthDbContext> >())); // These registrations are also needed since these are dealt with using non-standard construction factory.Register(new Registration <HttpContext>(resolver => HttpContext.Current)); factory.Register(new Registration <HttpContextBase>(resolver => new HttpContextWrapper(resolver.Resolve <HttpContext>()))); factory.Register(new Registration <HttpRequestBase>(resolver => resolver.Resolve <HttpContextBase>().Request)); factory.Register(new Registration <HttpResponseBase>(resolver => resolver.Resolve <HttpContextBase>().Response)); factory.Register(new Registration <HttpServerUtilityBase>(resolver => resolver.Resolve <HttpContextBase>().Server)); factory.Register(new Registration <HttpSessionStateBase>(resolver => resolver.Resolve <HttpContextBase>().Session)); var options = new IdentityServerOptions { SiteName = Strings.ThisServiceName, EnableWelcomePage = false, SigningCertificate = Cert.Load(config["cert:key"], log), Factory = factory, CspOptions = new CspOptions { ImgSrc = "'self' data:" }, AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions { // Try to prevent "request too long" errors when authenticating with Google, etc // https://github.com/IdentityServer/IdentityServer3/issues/1124 SignInMessageThreshold = 1, IdentityProviders = ConfigureIdentityProviders, LoginPageLinks = new LoginPageLink[] { new LoginPageLink { Text = "Register", //Href = "~/localregistration" Href = "localregistration" } } }, EventsOptions = new EventsOptions { RaiseSuccessEvents = true, RaiseErrorEvents = true, RaiseFailureEvents = true, RaiseInformationEvents = true } }; app.UseIdentityServer(options); // This must come after .UseIdentityServer so APIs can get identity values off the OWIN context WebSetup.SetupWebApi(app, kernel); }
public void Configuration(IAppBuilder app) { LogProvider.SetCurrentLogProvider(new CustomLogProvider()); app.Map("/login", coreApp => { var factory = new IdentityServerServiceFactory() .UseInMemoryClients(Clients.Get()) //.UseInMemoryUsers(Users.Get()) .UseInMemoryScopes(Scopes.Get()); //Set the options for the default view service var viewOptions = new DefaultViewServiceOptions(); #if DEBUG //Dont cache the views when we are testing viewOptions.CacheViews = false; #endif factory.ConfigureDefaultViewService(viewOptions); // different examples of custom user services //var userService = new RegisterFirstExternalRegistrationUserService(); //var userService = new ExternalRegistrationUserService(); //var userService = new EulaAtLoginUserService(); var userService = new LocalRegistrationUserService(); // note: for the sample this registration is a singletone (not what you want in production probably) factory.UserService = new Registration <IUserService>(resolver => userService); //Required for GPG custom interface //factory.ViewService = new Registration<IViewService, CustomViewService>(); factory.EventService = new Registration <IEventService, AuditEventService>(); var options = new IdentityServerOptions { SiteName = "GPG IdentityServer", SigningCertificate = LoadCertificate(), Factory = factory, AuthenticationOptions = new AuthenticationOptions { EnablePostSignOutAutoRedirect = true, IdentityProviders = ConfigureIdentityProviders, EnableSignOutPrompt = false, InvalidSignInRedirectUrl = ConfigurationManager.AppSettings["GpgWebServer"], LoginPageLinks = new List <LoginPageLink>() { new LoginPageLink() { Href = ConfigurationManager.AppSettings["GpgWebServerPasswordLink"], Text = "Reset your password", Type = "resetPassword" }, new LoginPageLink() { Href = ConfigurationManager.AppSettings["GpgWebServerRegisterLink"], Text = "Register", Type = "localRegistration" } } }, EventsOptions = new EventsOptions { RaiseSuccessEvents = true, RaiseErrorEvents = true, RaiseFailureEvents = true, RaiseInformationEvents = true } }; coreApp.UseIdentityServer(options); }); //app.Map("/login", idsrvApp => //{ // idsrvApp.UseIdentityServer(new IdentityServerOptions // { // SiteName = "GPG IdentityServer", // SigningCertificate = LoadCertificate(), // Factory = new IdentityServerServiceFactory() // .UseInMemoryUsers(Users.Get()) // .UseInMemoryClients(Clients.Get()) // .UseInMemoryScopes(Scopes.Get()), // AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions // { // EnablePostSignOutAutoRedirect = true, // IdentityProviders = ConfigureIdentityProviders, // LoginPageLinks = new List<LoginPageLink>() // { // new LoginPageLink() // { // Href = ConfigurationManager.AppSettings["GpgWebServerReminder"], // Text = "Forgotten Password?", // Type = "resetPassword" // }, // new LoginPageLink() // { // Href = ConfigurationManager.AppSettings["GpgWebServerRegister"], // Text = "Create New Account", // Type = "localRegistration" // } // } // } // }); //}); }
public void Configuration(IAppBuilder app) { #region customer login css //var viewOPtions = new DefaultViewServiceOptions(); //viewOPtions.CustomViewDirectory = string.Format(@"{0}\Templates\", AppDomain.CurrentDomain.BaseDirectory); //viewOPtions.Stylesheets.Add("/Content/Site.css"); //options.Factory.ConfigureDefaultViewService(viewOPtions); #endregion #region Role Scope EF config //ASP.Net identity user role... + identity server3 (EF client scope) var efOptions = new EntityFrameworkServiceOptions() { ConnectionString = "AuthServer", Schema = Constants.IdentityServerSchema, }; var factory = new IdentityServerServiceFactory(); factory.RegisterClientStore(efOptions); factory.RegisterScopeStore(efOptions); //factory.UseInMemoryUsers(InMemoryUsers.GetAllUsers()); //factory.UserService = new Registration<IdentityServer3.Core.Services.IUserService>(); #endregion #region User EF config //IdentityDbContext identityDbContext = new IdentityDbContext("AuthServer"); IdentityDbContext identityDbContext = new CustomIdentityDbContext("AuthServer"); UserManager <IdentityUser> userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(identityDbContext)); RoleManager <IdentityRole> roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(identityDbContext)); var userService = new AspNetIdentityUserService <IdentityUser, string>(userManager); factory.UserService = new Registration <IdentityServer3.Core.Services.IUserService>(userService); #endregion //factory.RegisterConfigurationServices(efOptions); #region Token and Cache config factory.RegisterOperationalServices(efOptions);//database store token factory.ConfigureClientStoreCache(); factory.ConfigureScopeStoreCache(); factory.ConfigureUserServiceCache(); var clearToken = new TokenCleanup(efOptions, 60); clearToken.Start(); #endregion #region IdentityServer config var options = new IdentityServerOptions() { Factory = factory, RequireSsl = false, AuthenticationOptions = new AuthenticationOptions { EnablePostSignOutAutoRedirect = true, IdentityProviders = IdentityProviderManager.ConfigureIdentityProviders, }, SigningCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(string.Format(@"{0}\certificate\server.pfx", AppDomain.CurrentDomain.BaseDirectory), "4022042"), }; #endregion //SampleDataProvider.InitClientAndScopeSampleDatas(efOptions);//init some data app.ConfigureManagerService();//for Identity Manager Pages app.UseIdentityServer(options); }
public void Configuration(IAppBuilder app) { // Configure the db context and user manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); app.Map("/identity", idsrvApp => { var corsPolicyService = new DefaultCorsPolicyService() { AllowAll = true }; var defaultViewServiceOptions = new DefaultViewServiceOptions(); defaultViewServiceOptions.CacheViews = false; var idServerServiceFactory = new IdentityServerServiceFactory() .UseInMemoryClients(CustomClients.Get()) .UseInMemoryScopes(CustomScopes.Get()); //.UseInMemoryUsers(CustomUsers.Get()); idServerServiceFactory.CorsPolicyService = new Registration <IdentityServer3.Core.Services.ICorsPolicyService>(corsPolicyService); idServerServiceFactory.ConfigureDefaultViewService(defaultViewServiceOptions); idServerServiceFactory.Register(new Registration <ApplicationDbContext>()); idServerServiceFactory.Register(new Registration <UserStore <ApplicationUser> >(resolver => { return(new UserStore <ApplicationUser>(resolver.Resolve <ApplicationDbContext>())); })); idServerServiceFactory.Register(new Registration <UserManager <ApplicationUser> >(resolver => { return(new ApplicationUserManager(resolver.Resolve <UserStore <ApplicationUser> >())); })); idServerServiceFactory.UserService = new Registration <IUserService, CustomUserService>(); var options = new IdentityServerOptions { Factory = idServerServiceFactory, // Just for Angular 2 App testing. RequireSsl = false, SiteName = "TripCompany Security Token Service", SigningCertificate = LoadCertificate(), IssuerUri = DBSP.RememberMe.Identity.Constants.TripGalleryIssuerUri, PublicOrigin = DBSP.RememberMe.Identity.Constants.TripGallerySTSOrigin, AuthenticationOptions = new AuthenticationOptions() { EnablePostSignOutAutoRedirect = true, LoginPageLinks = new List <LoginPageLink>() { new LoginPageLink() { Type = "createaccount", Text = "Create a new account", Href = "~/createuseraccount" } } }, CspOptions = new CspOptions() { Enabled = false // once available, leave Enabled at true and use: // FrameSrc = "https://localhost:44318 https://localhost:44316" // or // FrameSrc = "*" for all URI's. } }; idsrvApp.UseIdentityServer(options); }); }
public static void RegisterAsAutofacResolvable(this IdentityServerServiceFactory factory, Type type, RegistrationContext context, Func <ILifetimeScope, object> resolveWithLifetimeScopeFunc = null, Func <IOwinContext, object> resolveWithOwinContextFunc = null, string name = null) { factory.Register(CreateRegistration(type, context, resolveWithLifetimeScopeFunc, resolveWithOwinContextFunc, name)); }
public void Configuration(IAppBuilder app) { app.Map("/oauth", coreApp => { var factory = new IdentityServerServiceFactory(); factory.ClaimsProvider = new Registration <IClaimsProvider, CustomClaimProvider>(); var clientStorageProvider = new ClientStorage(); factory.ClientStore = new Registration <IClientStore>(resolver => clientStorageProvider); var scopeStorageProvider = new ScopeProvider(); factory.ScopeStore = new Registration <IScopeStore>(resolver => scopeStorageProvider); //currently by defult supported for angular only factory.ViewService = new Registration <IViewService, CustomAngularViewService>(); // different examples of custom user services //var userService = new RegisterFirstExternalRegistrationUserService(); //var userService = new ExternalRegistrationUserService(); var userService = new EulaAtLoginUserService(); // var userService = new LocalRegistrationUserService(); //for normal // factory.UserService = new Registration<IUserService, EulaAtLoginUserService>(); factory.UserService = new Registration <IUserService>(resolver => userService); //for custom login service // factory.UserService = new Registration<IUserService, LocalRegistrationUserService>(); factory.Register(new Registration <TestController>(typeof(TestController))); var options = new IdentityServerOptions { EnableWelcomePage = false, //Endpoints = new EndpointOptions() //{ // EnableUserInfoEndpoint = true, // EnableTokenEndpoint = true, // EnableAuthorizeEndpoint = true, // EnableClientPermissionsEndpoint = true, // EnableTokenRevocationEndpoint = true, // EnableAccessTokenValidationEndpoint = true //}, SiteName = "Identity Server", SigningCertificate = Certificate.Get(), Factory = factory, ////this line for custom login //AuthenticationOptions = new AuthenticationOptions //{ //}, AuthenticationOptions = new AuthenticationOptions { RequireSignOutPrompt = false, // IdentityProviders = ConfigureAdditionalIdentityProviders, //LoginPageLinks = new LoginPageLink[] { // new LoginPageLink{ // Text = "Register", // //Href = "~/localregistration" // Href = "localregistration" // } //} }, EventsOptions = new EventsOptions { RaiseSuccessEvents = true, RaiseErrorEvents = true, RaiseFailureEvents = true, RaiseInformationEvents = true } }; coreApp.UseIdentityServer(options); }); //JwtSecurityTokenHandler.InboundClaimTypeMap.Clear(); //app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions //{ // Authority = "https://localhost:44300/core", // RequiredScopes = new[] { "openId","write","email","profile" }, // // client credentials for the introspection endpoint // ClientId = "write", // ClientSecret = "secret" //}); //app.UseWebApi(WebApiConfig.Register()); }
/// <summary> /// Initializes a new instance of the <see cref="WsFederationServiceFactory"/> class. /// </summary> /// <param name="factory">The factory.</param> public WsFederationServiceFactory(IdentityServerServiceFactory factory) { UserService = factory.UserService; }
public Options(IdentityServerServiceFactory factory) { Factory = factory; }
public virtual void Configure(IAppBuilder owinApp) { if (owinApp == null) { throw new ArgumentNullException(nameof(owinApp)); } owinApp.Map("/core", coreApp => { LogProvider.SetCurrentLogProvider(DependencyManager.Resolve <ILogProvider>()); AppEnvironment activeAppEnvironment = AppEnvironmentProvider.GetActiveAppEnvironment(); IdentityServerServiceFactory factory = new IdentityServerServiceFactory() .UseInMemoryClients(DependencyManager.Resolve <IClientProvider>().GetClients().ToArray()) .UseInMemoryScopes(ScopesProvider.GetScopes()); factory.UserService = new Registration <IUserService>(DependencyManager.Resolve <IUserService>()); factory.EventService = new Registration <IEventService>(EventService); factory.ViewService = new Registration <IViewService>(DependencyManager.Resolve <IViewService>()); factory.RedirectUriValidator = new Registration <IRedirectUriValidator>(RedirectUriValidator); bool requireSslConfigValue = activeAppEnvironment.GetConfig("RequireSsl", defaultValueOnNotFound: false); string identityServerSiteName = activeAppEnvironment.GetConfig("IdentityServerSiteName", $"{activeAppEnvironment.AppInfo.Name} Identity Server"); IdentityServerOptions identityServerOptions = new IdentityServerOptions { SiteName = identityServerSiteName, SigningCertificate = CertificateProvider.GetSingleSignOnCertificate(), Factory = factory, RequireSsl = requireSslConfigValue, EnableWelcomePage = activeAppEnvironment.DebugMode == true, IssuerUri = activeAppEnvironment.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 } }; coreApp.UseIdentityServer(identityServerOptions); }); }
public IdentityServerOptions GetServerOptions() { var factory = new IdentityServerServiceFactory(); var knownClientStore = new KnownClientStore(identityManagerUri, identityAdminUri, identityServerUri); factory.ClientStore = new Registration <IClientStore>( new CompositeClientStore(new IClientStore[] { new ClientStore(new ClientConfigurationDbContext("ClientsScopes")), // TODO: get connection string name from config knownClientStore })); factory.ScopeStore = new Registration <IScopeStore>( new CompositeScopeStore(new IScopeStore[] { new ScopeStore(new ScopeConfigurationDbContext("ClientsScopes")), // TODO: get connection string name from config new KnownScopeStore() })); factory.UserService = new Registration <IUserService>( new CompositeUserService(new IUserService[] { new KnownUserService(this.adminUsername, this.adminPassword), new ClaimsUserService(new NullClaimsService(), userService) })); factory.CorsPolicyService = new Registration <ICorsPolicyService>( new CompositeCorsPolicyService(new ICorsPolicyService[] { new ClientConfigurationCorsPolicyService(new ClientConfigurationDbContext("ClientsScopes")), // TODO: get connection string name from config new InMemoryCorsPolicyService(knownClientStore.GetClients()) })); //We can choose how to display the login screen LoadViewService(factory); return(new IdentityServerOptions { SiteName = "IdentityServer v3", SigningCertificate = Cert.Load(typeof(IOwinBootstrapper).Assembly, "Cert", "idsrv3test.pfx", "idsrv3test"), Endpoints = new EndpointOptions { EnableCspReportEndpoint = true }, AuthenticationOptions = new AuthenticationOptions { IdentityProviders = externalIdentityProviderService.UseExternalIdentityProviders, //Registration link on login page LoginPageLinks = new LoginPageLink[] { new LoginPageLink { Text = "Register", Href = "localregistration" } } }, LoggingOptions = new LoggingOptions { EnableHttpLogging = true, EnableKatanaLogging = true, EnableWebApiDiagnostics = true, WebApiDiagnosticsIsVerbose = true }, Factory = factory }); }
public static void ConfigureClient(this IdentityServerServiceFactory factory, RavenServiceOptions options) { options.Store.Conventions.RegisterIdConvention <Client>( (dbname, commands, client) => options.Store.Conventions.FindTypeTagName(typeof(Client)) + "/" + client.ClientId); factory.Register(new Registration <IClientStore, ClientStore>()); }
public void Configuration(IAppBuilder app) { //var factory2 = new IdentityServerServiceFactory(); //LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider()); //var factory = InMemoryFactory.Create( // scopes: Scopes.Get(), // clients: Clients.Get(), // users: Users2.Get() // ); var factory = new IdentityServerServiceFactory(); var scopeStore = new InMemoryScopeStore(Scopes.Get()); factory.ScopeStore = new Registration <IScopeStore>(scopeStore); var clientStore = new InMemoryClientStore(Clients.Get()); factory.ClientStore = new Registration <IClientStore>(clientStore); factory.TokenService = new Registration <ITokenService>(typeof(MyCustomTokenService)); factory.RefreshTokenStore = new Registration <IRefreshTokenStore>(typeof(MyCustomRefreshTokenStore)); factory.CustomTokenValidator = new Registration <ICustomTokenValidator>(new MyCustomTokenValidator()); factory.TokenHandleStore = new Registration <ITokenHandleStore>(new MyCustomTokenHandleStore()); factory.ConfigureUserService("AspId"); LogProvider.SetCurrentLogProvider(new NLogLogProvider()); //LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider()); //factory.TokenHandleStore = new Registration<ITokenHandleStore>(); //factory.RefreshTokenStore = new Registration<IRefreshTokenStore>(); //factory.CustomTokenValidator = new Registration<ICustomTokenValidator>(new MyCustomTokenValidator()); //factory.Register(new Registration<IUserService, MyCustomUserService>()); //factory.Register(new Registration<IMyCustomLogger, MyCustomLogger>()); //factory.UserService = new Registration<IUserService>(typeof(IUserService)); var options = new IdentityServerOptions { Factory = factory, //IssuerUri = "https://idsrv3.com", SiteName = "Thinktecture IdentityServer3 Halo", SigningCertificate = Certificate.Get(), RequireSsl = false, CspOptions = new CspOptions { Enabled = true, }, Endpoints = new EndpointOptions { EnableAccessTokenValidationEndpoint = true, EnableTokenEndpoint = true, EnableTokenRevocationEndpoint = true, EnableIdentityTokenValidationEndpoint = true, //remove in production EnableDiscoveryEndpoint = true, EnableAuthorizeEndpoint = false, EnableClientPermissionsEndpoint = false, EnableCspReportEndpoint = false, EnableEndSessionEndpoint = false, EnableCheckSessionEndpoint = false, EnableUserInfoEndpoint = false }, AuthenticationOptions = new AuthenticationOptions { EnableLocalLogin = true, EnableLoginHint = false, }, LoggingOptions = new LoggingOptions { EnableHttpLogging = true, EnableWebApiDiagnostics = true, IncludeSensitiveDataInLogs = true, WebApiDiagnosticsIsVerbose = true }, EnableWelcomePage = false, IssuerUri = "https://HFL0100:44333" }; options.CorsPolicy.AllowedOrigins.Add("http://localhost:14869/"); app.UseHsts(); app.UseIdentityServer(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.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.RegisterDefaultInstance <ICorsPolicyService, DefaultCorsPolicyService>(fact.CorsPolicyService); builder.RegisterDefaultType <IPasswordResetService, DefaultPasswordResetService>(fact.PasswordResetService); builder.RegisterDefaultType <IClaimsProvider, DefaultClaimsProvider>(fact.ClaimsProvider); builder.RegisterDefaultType <ITokenService, DefaultTokenService>(fact.TokenService); builder.RegisterDefaultType <IRefreshTokenService, DefaultRefreshTokenService>(fact.RefreshTokenService); builder.RegisterDefaultType <ICustomRequestValidator, DefaultCustomRequestValidator>(fact.CustomRequestValidator); builder.RegisterDefaultType <IExternalClaimsFilter, NopClaimsFilter>(fact.ExternalClaimsFilter); builder.RegisterDefaultType <ICustomTokenValidator, DefaultCustomTokenValidator>(fact.CustomTokenValidator); builder.RegisterDefaultType <ICustomTokenResponseGenerator, DefaultCustomTokenResponseGenerator>(fact.CustomTokenResponseGenerator); builder.RegisterDefaultType <IConsentService, DefaultConsentService>(fact.ConsentService); builder.RegisterDefaultType <IAuthenticationSessionValidator, DefaultAuthenticationSessionValidator>(fact.AuthenticationSessionValidator); // todo remove in next major version if (fact.TokenSigningService != null) { builder.Register(fact.TokenSigningService); } else { builder.Register(new Registration <ITokenSigningService>(r => new DefaultTokenSigningService(r.Resolve <ISigningKeyService>()))); } builder.RegisterDefaultType <ISigningKeyService, DefaultSigningKeyService>(fact.SigningKeyService); 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); // register custom grant validators builder.RegisterType <CustomGrantValidator>(); if (fact.CustomGrantValidators.Any()) { foreach (var val in fact.CustomGrantValidators) { builder.Register(val); } } // register secret parsing/validation plumbing builder.RegisterType <SecretValidator>(); builder.RegisterType <SecretParser>(); foreach (var parser in fact.SecretParsers) { builder.Register(parser); } foreach (var validator in fact.SecretValidators) { builder.Register(validator); } // register view service plumbing if (fact.ViewService == null) { fact.ViewService = new DefaultViewServiceRegistration(); } builder.Register(fact.ViewService); // 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>(); // validators builder.RegisterType <TokenRequestValidator>(); builder.RegisterType <AuthorizeRequestValidator>(); builder.RegisterType <TokenValidator>(); builder.RegisterType <EndSessionRequestValidator>(); builder.RegisterType <BearerTokenUsageValidator>(); builder.RegisterType <ScopeValidator>(); builder.RegisterType <TokenRevocationRequestValidator>(); builder.RegisterType <IntrospectionRequestValidator>(); builder.RegisterType <ScopeSecretValidator>(); builder.RegisterType <ClientSecretValidator>(); // processors builder.RegisterType <TokenResponseGenerator>(); builder.RegisterType <AuthorizeResponseGenerator>(); builder.RegisterType <AuthorizeInteractionResponseGenerator>(); builder.RegisterType <UserInfoResponseGenerator>(); builder.RegisterType <EndSessionResponseGenerator>(); builder.RegisterType <IntrospectionResponseGenerator>(); // 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>())); builder.Register(c => new ClientListCookie(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 void Configuration(IAppBuilder app) { //app.UseStaticFiles(new StaticFileOptions //{ // RequestPath = new PathString("/core/content"), // FileSystem = new PhysicalFileSystem("Content") //}); //DefaultViewServiceConfiguration // style override: // https://github.com/IdentityServer/IdentityServer3/issues/715 app.Map("/identity", idSvrApp => { var corsPolicyService = new DefaultCorsPolicyService() { AllowAll = true }; var idServerServiceFactory = new IdentityServerServiceFactory() .UseInMemoryClients(Clients.Get()) .UseInMemoryScopes(Scopes.Get()); // .UseInMemoryUsers(Users.Get()) // for dev/testing // To completely customze the login screen, go here: //https://identityserver.github.io/Documentation/docsv2/advanced/customizingViews.html idServerServiceFactory.CorsPolicyService = new Registration <IdentityServer3.Core.Services.ICorsPolicyService>(corsPolicyService); var cnString = ConfigurationManager.ConnectionStrings["Login"].ConnectionString; var pepper = ConfigurationManager.AppSettings["Pepper"]; var accountRepo = new AccountRepository(cnString, pepper); var userService = new UserService(accountRepo); idServerServiceFactory.UserService = new Registration <IUserService>(resolver => userService); idServerServiceFactory.ViewService = new Registration <IViewService, ViewService>(); var options = new IdentityServerOptions { Factory = idServerServiceFactory, SiteName = "Ntcc Steward Security Service", IssuerUri = ConfigurationManager.AppSettings["NtccStewardIssuerUri"], // does not have to be an existing uri PublicOrigin = ConfigurationManager.AppSettings["NtccStewardStsOrigin"], SigningCertificate = LoadCertificate(), // certificate that is used for encrpting token, not ssl AuthenticationOptions = new AuthenticationOptions() { EnablePostSignOutAutoRedirect = true, LoginPageLinks = new List <LoginPageLink>() { new LoginPageLink() { Type = "createAccount", Text = "Request an Account", Href = "~/Account" } } }, CspOptions = new CspOptions { Enabled = false } //ProtocolLogoutUrls= new List<string>() { //} }; idSvrApp.UseIdentityServer(options); }); }
/// <summary> /// Initializes a new instance of the <see cref="SiteFinityServiceFactory"/> class. /// </summary> /// <param name="factory">The factory.</param> public SiteFinityServiceFactory(IdentityServerServiceFactory factory) { UserService = factory.UserService; }
/// <summary> /// Register the configuration services, namely the client and scope stores /// </summary> public static void RegisterConfigurationServices(this IdentityServerServiceFactory factory, DocumentDbServiceOptions options) { factory.RegisterClientStore(options); factory.RegisterScopeStore(options); }
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); }); }
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()); }