/// <summary> /// Adds Dashboard UI middleware to the OWIN request processing pipeline with the /// specified parameters and antiforgery service. /// </summary> /// <param name="builder">OWIN application builder.</param> /// <param name="pathMatch">Path prefix for middleware to use, e.g. "/hangfire".</param> /// <param name="options">Options for Dashboard UI.</param> /// <param name="storage">Job storage to use by Dashboard IO.</param> /// <param name="antiforgery">Antiforgery service.</param> /// /// <exception cref="ArgumentNullException"><paramref name="builder"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="pathMatch"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="options"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="storage"/> is null.</exception> /// /// <remarks> /// Please see <see cref="AppBuilderExtensions"/> for details and examples. /// </remarks> public static IAppBuilder UseHangfireDashboard( [NotNull] this IAppBuilder builder, [NotNull] string pathMatch, [NotNull] DashboardOptions options, [NotNull] JobStorage storage, [CanBeNull] IOwinDashboardAntiforgery antiforgery) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (pathMatch == null) { throw new ArgumentNullException(nameof(pathMatch)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } if (storage == null) { throw new ArgumentNullException(nameof(storage)); } SignatureConversions.AddConversions(builder); builder.Map(pathMatch, subApp => subApp .UseOwin() .UseHangfireDashboard(options, storage, DashboardRoutes.Routes, antiforgery)); return(builder); }
public static void UseIdentityManager(this IAppBuilder app, IdentityManagerConfiguration config) { if (app == null) { throw new ArgumentNullException("app"); } if (config == null) { throw new ArgumentNullException("config"); } config.Validate(); if (config.SecurityMode == SecurityMode.LocalMachine) { var local = new LocalAuthenticationOptions(config.AdminRoleName); app.Use <LocalAuthenticationMiddleware>(local); } else if (config.SecurityMode == SecurityMode.OAuth2) { if (config.OAuth2Configuration.SigningCert != null) { app.UseJsonWebToken(config.OAuth2Configuration.Issuer, config.OAuth2Configuration.Audience, config.OAuth2Configuration.SigningCert); } else { app.UseJsonWebToken(config.OAuth2Configuration.Issuer, config.OAuth2Configuration.Audience, config.OAuth2Configuration.SigningKey); } app.Use(async(ctx, next) => { await next(); }); } if (!config.DisableUserInterface) { app.UseFileServer(new FileServerOptions { RequestPath = new PathString("/assets"), FileSystem = new EmbeddedResourceFileSystem(typeof(AppBuilderExtensions).Assembly, "Thinktecture.IdentityManager.Assets") }); app.UseFileServer(new FileServerOptions { RequestPath = new PathString("/assets/libs/fonts"), FileSystem = new EmbeddedResourceFileSystem(typeof(AppBuilderExtensions).Assembly, "Thinktecture.IdentityManager.Assets.Content.fonts") }); app.UseStageMarker(PipelineStage.MapHandler); } SignatureConversions.AddConversions(app); var httpConfig = new HttpConfiguration(); WebApiConfig.Configure(httpConfig, config); app.UseWebApi(httpConfig); app.UseStageMarker(PipelineStage.MapHandler); }
/// <summary> /// Extension method to configure IdentityServer in the hosting application. /// </summary> /// <param name="app">The application.</param> /// <param name="options">The <see cref="Thinktecture.IdentityServer.Core.Configuration.IdentityServerOptions"/>.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// app /// or /// options /// </exception> public static IAppBuilder UseIdentityServer(this IAppBuilder app, IdentityServerOptions options) { if (app == null) { throw new ArgumentNullException("app"); } if (options == null) { throw new ArgumentNullException("options"); } options.Validate(); // turn off weird claim mappings for JWTs JwtSecurityTokenHandler.InboundClaimTypeMap = ClaimMappings.None; JwtSecurityTokenHandler.OutboundClaimTypeMap = ClaimMappings.None; if (options.RequireSsl) { app.Use <RequireSslMiddleware>(); } app.ConfigureRequestId(); options.ProtocolLogoutUrls.Add(Constants.RoutePaths.Oidc.EndSessionCallback); app.ConfigureDataProtectionProvider(options); app.ConfigureIdentityServerBaseUrl(options.PublicOrigin); app.ConfigureIdentityServerIssuer(options); app.UseCors(options.CorsPolicy); app.ConfigureCookieAuthentication(options.AuthenticationOptions.CookieOptions, options.DataProtector); var container = AutofacConfig.Configure(options); app.Use <AutofacContainerMiddleware>(container); if (options.PluginConfiguration != null) { options.PluginConfiguration(app, options); } if (options.AuthenticationOptions.IdentityProviders != null) { options.AuthenticationOptions.IdentityProviders(app, Constants.ExternalAuthenticationType); } app.UseEmbeddedFileServer(); SignatureConversions.AddConversions(app); app.UseWebApi(WebApiConfig.Configure(options)); using (var child = container.CreateScopeWithEmptyOwinContext()) { var eventSvc = child.Resolve <IEventService>(); DoStartupDiagnostics(options, eventSvc); } return(app); }
internal void Initialize(Action <IAppBuilder> startup) { Capabilities = new ConcurrentDictionary <string, object>(); var builder = new AppBuilder(); SignatureConversions.AddConversions(builder); builder.Properties[Constants.OwinVersionKey] = Constants.OwinVersion; builder.Properties[Constants.HostTraceOutputKey] = TraceTextWriter.Instance; builder.Properties[Constants.HostAppNameKey] = HostingEnvironment.SiteName; builder.Properties[Constants.HostOnAppDisposingKey] = OwinApplication.ShutdownToken; builder.Properties[Constants.HostReferencedAssemblies] = new ReferencedAssembliesWrapper(); builder.Properties[Constants.ServerCapabilitiesKey] = Capabilities; builder.Properties[Constants.SecurityDataProtectionProvider] = new MachineKeyDataProtectionProvider().ToOwinFunction(); builder.SetLoggerFactory(new DiagnosticsLoggerFactory()); Capabilities[Constants.ServerNameKey] = Constants.ServerName; Capabilities[Constants.ServerVersionKey] = Constants.ServerVersion; Capabilities[Constants.SendFileVersionKey] = Constants.SendFileVersion; #if !NET40 DetectWebSocketSupportStageOne(); #endif try { startup(builder); } catch (Exception ex) { _trace.WriteError(Resources.Trace_EntryPointException, ex); throw; } AppFunc = (AppFunc)builder.Build(typeof(AppFunc)); }
public void Configuration(IAppBuilder app) { SetNuGetNotRunningInVisualStudio(); SignatureConversions.AddConversions(app); Settings = CreateSettings(); Start(app, CreateContainer(app)); }
/// <summary> /// Add the WS-Federation plugin to the IdentityServer pipeline. /// </summary> /// <param name="app">The appBuilder.</param> /// <param name="options">The options.</param> /// <returns>The appBuilder</returns> /// <exception cref="System.ArgumentNullException">options</exception> public static IAppBuilder UseSiteFinityPlugin(this IAppBuilder app, SiteFinityPluginOptions options) { if (options == null) { throw new ArgumentNullException("options"); } options.Validate(); //options.IdentityServerOptions.ProtocolLogoutUrls.Add(options.LogoutUrl); app.Map(options.MapPath, sitefinityApp => { //sitefinityApp.UseCookieAuthentication(new CookieAuthenticationOptions //{ // AuthenticationType = WsFederationPluginOptions.CookieName, // AuthenticationMode = AuthenticationMode.Passive, // CookieName = options.IdentityServerOptions.AuthenticationOptions.CookieOptions.Prefix + WsFederationPluginOptions.CookieName, //}); sitefinityApp.Use <AutofacContainerMiddleware>(AutofacConfig.Configure(options)); SignatureConversions.AddConversions(app); sitefinityApp.UseWebApi(WebApiConfig.Configure(options)); }); return(app); }
public static IAppBuilder UseModuleActivator( [NotNull] this IAppBuilder builder, [NotNull] string module, [NotNull] DashboardOptions options, [NotNull] RouteCollection routes ) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (module == null) { throw new ArgumentNullException(nameof(module)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } SignatureConversions.AddConversions(builder); builder.Map(module, subApp => subApp.UseOwin().UseModuleActivator(options, routes)); return(builder); }
public static IAppBuilder UseHangfireDashboard( [NotNull] this IAppBuilder builder, [NotNull] string pathMatch, [NotNull] DashboardOptions options, [NotNull] JobStorage storage) { if (builder == null) { throw new ArgumentNullException("builder"); } if (pathMatch == null) { throw new ArgumentNullException("pathMatch"); } if (options == null) { throw new ArgumentNullException("options"); } if (storage == null) { throw new ArgumentNullException("storage"); } SignatureConversions.AddConversions(builder); builder.Map(pathMatch, subApp => subApp .UseOwin() .UseHangfireDashboard(options, storage, DashboardRoutes.Routes)); return(builder); }
public static IAppBuilder UsePdfview( [NotNull] this IAppBuilder builder, [NotNull] string pathMatch, [NotNull] DashboardOptions options ) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (pathMatch == null) { throw new ArgumentNullException(nameof(pathMatch)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } SignatureConversions.AddConversions(builder); Resource.Setting.ModuleName = pathMatch.Trim('/').Replace("/", "."); builder.Map(pathMatch, subApp => subApp.UseOwin().UseModuleActivator(options, Resource.Setting.Routes)); return(builder); }
public static IAppBuilder UseDashboard( this IAppBuilder builder, string pathMatch = null, DashboardOptions options = null, RouteCollection routes = null) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (string.IsNullOrEmpty(pathMatch)) { pathMatch = "/dashboard"; } if (options == null) { options = new DashboardOptions(); } if (routes == null) { routes = new RouteCollectionBuilder().Routes; } SignatureConversions.AddConversions(builder); builder.Map(pathMatch, subApp => subApp .UseOwin() .UseDashboard(options, routes)); return(builder); }
public void Configuration(IAppBuilder appBuilder) { SignatureConversions.AddConversions(appBuilder); HttpConfiguration httpConfiguration = new HttpConfiguration(); WebApiConfig.Register(httpConfiguration); appBuilder.UseWebApi(httpConfiguration); }
public static void UseIdentityManager(this IAppBuilder app, IdentityManagerOptions options) { if (app == null) { throw new ArgumentNullException("app"); } if (options == null) { throw new ArgumentNullException("config"); } app.SetLoggerFactory(new LibLogLoggerFactory()); Logger.Info("Starting IdentityManager configuration"); options.Validate(); app.Use(async(ctx, next) => { if (!ctx.Request.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) && options.SecurityConfiguration.RequireSsl) { ctx.Response.Write("HTTPS required"); } else { await next(); } }); var container = AutofacConfig.Configure(options); app.Use <AutofacContainerMiddleware>(container); options.SecurityConfiguration.Configure(app); if (!options.DisableUserInterface) { app.UseFileServer(new FileServerOptions { RequestPath = new PathString("/assets"), FileSystem = new EmbeddedResourceFileSystem(typeof(IdentityManagerAppBuilderExtensions).Assembly, "IdentityManager.Assets") }); app.UseFileServer(new FileServerOptions { RequestPath = new PathString("/assets/libs/fonts"), FileSystem = new EmbeddedResourceFileSystem(typeof(IdentityManagerAppBuilderExtensions).Assembly, "IdentityManager.Assets.Content.fonts") }); app.UseStageMarker(PipelineStage.MapHandler); } SignatureConversions.AddConversions(app); app.UseWebApi(WebApiConfig.Configure(options)); app.UseStageMarker(PipelineStage.MapHandler); // clears out the OWIN logger factory so we don't recieve other hosting related logs app.Properties["server.LoggerFactory"] = null; }
/// <summary> /// Extension method for adding the windows authentication service to the pipeline /// </summary> /// <param name="app">The app builder.</param> /// <param name="options">The options class.</param> /// <returns></returns> public static IAppBuilder UseWindowsAuthenticationService(this IAppBuilder app, WindowsAuthenticationOptions options) { Logger.Info("Starting configuration."); app.ConfigureBaseUrl(options.PublicOrigin); if (options.EnableWsFederationEndpoint) { Logger.Info("Adding WS-Federation endpoint"); var webApiConfig = new HttpConfiguration(); webApiConfig.MapHttpAttributeRoutes(); webApiConfig.Services.Add(typeof(IExceptionLogger), new LogProviderExceptionLogger()); webApiConfig.Services.Replace(typeof(IHttpControllerTypeResolver), new ControllerResolver()); var builder = new ContainerBuilder(); builder.RegisterInstance(options); builder.RegisterApiControllers(typeof(AuthenticationController).Assembly); webApiConfig.DependencyResolver = new AutofacWebApiDependencyResolver(builder.Build()); app.UseWebApi(webApiConfig); } if (options.EnableOAuth2Endpoint) { Logger.Info("Adding OAuth2 endpoint"); app.Use(async(context, next) => { if (context.Request.Uri.AbsolutePath.EndsWith("/token", StringComparison.OrdinalIgnoreCase)) { if (context.Authentication.User == null || !context.Authentication.User.Identity.IsAuthenticated) { context.Response.StatusCode = 401; return; } } await next(); }); app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), Provider = new WindowsAuthenticationTokenProvider(options), AccessTokenFormat = new JwtFormat(options), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(options.TokenLifeTime) }); } SignatureConversions.AddConversions(app); Logger.Info("Configuration done."); return(app); }
/// <summary> /// Initializes a new instance of the the type. /// </summary> public AppBuilder() { _properties = new Dictionary <string, object>(); _conversions = new Dictionary <Tuple <Type, Type>, Delegate>(); _middleware = new List <Tuple <Type, Delegate, object[]> >(); _properties[Constants.BuilderAddConversion] = new Action <Delegate>(AddSignatureConversion); _properties[Constants.BuilderDefaultApp] = NotFound; SignatureConversions.AddConversions(this); }
/// <summary> /// 自定义其他设置 /// </summary> /// <param name="builder"></param> /// <param name="pathMatch"></param> /// <param name="options"></param> /// <returns></returns> public static IAppBuilder UseLayimApi(this IAppBuilder builder, string pathMatch, LayimOptions options, LayimStorage storage) { Error.ThrowIfNull(pathMatch, nameof(pathMatch)); Error.ThrowIfNull(options, nameof(options)); SignatureConversions.AddConversions(builder); builder.Map(pathMatch, appBuilder => appBuilder .UseOwin() .UseLayimApi(storage, options, LayimRoutes.Routes)); return(builder); }
private static void RunAzureSignalRCore(IAppBuilder builder, string applicationName, HubConfiguration configuration, ServiceOptions options) { // applicationName is case insensitive, it will be lower cased in the service side if (string.IsNullOrEmpty(applicationName)) { throw new ArgumentException(nameof(applicationName), "Empty application name is not allowed."); } if (configuration == null) { // Keep the same as SignalR's exception throw new ArgumentException("A configuration object must be specified."); } var resolver = configuration.Resolver ?? throw new ArgumentException("A dependency resolver must be specified."); // Ensure we have the conversions for MS.Owin so that // the app builder respects the OwinMiddleware base class SignatureConversions.AddConversions(builder); // ServiceEndpointManager needs the logger var loggerFactory = new LoggerFactory(); var hubs = GetAvailableHubNames(configuration); var endpoint = new ServiceEndpointManager(options, loggerFactory); configuration.Resolver.Register(typeof(IServiceEndpointManager), () => endpoint); // Get the one from DI or new a default one var router = configuration.Resolver.Resolve <IEndpointRouter>() ?? new DefaultEndpointRouter(); builder.Use <NegotiateMiddleware>(configuration, applicationName, endpoint, router, options, loggerFactory); builder.RunSignalR(configuration); // Fetch the trace manager from DI and add logger provider var traceManager = configuration.Resolver.Resolve <ITraceManager>(); if (traceManager != null) { loggerFactory.AddProvider(new TraceManagerLoggerProvider(traceManager)); } var dispatcher = PrepareAndGetDispatcher(configuration, options, endpoint, router, applicationName, hubs, loggerFactory); if (dispatcher != null) { // Start the server->service connection asynchronously _ = dispatcher.StartAsync(); } }
/// <summary> /// Initializes a new instance of the the type. /// </summary> public AppBuilder() { _properties = new Dictionary <string, object>(); _conversions = new Dictionary <Tuple <Type, Type>, Delegate>(); _middleware = new List <Tuple <Type, Delegate, object[]> >(); _properties[Constants.BuilderAddConversion] = new Action <Delegate>(AddSignatureConversion); _properties[Constants.BuilderDefaultApp] = NotFound; // 添加两个conversion到_conversions,调用本身的方法AddSignatureConversion // 1. 将OwinMiddleware转为AppFunc // 2. 将AppFunc转为OwinMiddleware SignatureConversions.AddConversions(this); }
public static IAppBuilder UseIdentityServer(this IAppBuilder app, IdentityServerOptions options) { if (app == null) { throw new ArgumentNullException("app"); } if (options == null) { throw new ArgumentNullException("options"); } options.Validate(); // turn off weird claim mappings for JWTs JwtSecurityTokenHandler.InboundClaimTypeMap = ClaimMappings.None; JwtSecurityTokenHandler.OutboundClaimTypeMap = ClaimMappings.None; if (options.RequireSsl) { app.Use <RequireSslMiddleware>(); } options.ProtocolLogoutUrls.Add(Constants.RoutePaths.Oidc.EndSessionCallback); app.ConfigureDataProtectionProvider(options); app.ConfigureIdentityServerBaseUrl(options.PublicHostName); app.ConfigureIdentityServerIssuer(options); app.UseCors(options.CorsPolicy); app.ConfigureCookieAuthentication(options.AuthenticationOptions.CookieOptions, options.DataProtector); if (options.PluginConfiguration != null) { options.PluginConfiguration(app, options); } if (options.AuthenticationOptions.IdentityProviders != null) { options.AuthenticationOptions.IdentityProviders(app, Constants.ExternalAuthenticationType); } app.UseEmbeddedFileServer(); app.Use <AutofacContainerMiddleware>(AutofacConfig.Configure(options)); SignatureConversions.AddConversions(app); app.UseWebApi(WebApiConfig.Configure(options)); return(app); }
public static void UseIdentityManager(this IAppBuilder app, IdentityManagerConfiguration config) { if (app == null) { throw new ArgumentNullException("app"); } if (config == null) { throw new ArgumentNullException("config"); } config.Validate(); if (config.SecurityMode == SecurityMode.Local) { app.Use(async(ctx, next) => { var localAddresses = new string[] { "127.0.0.1", "::1", ctx.Request.LocalIpAddress }; if (localAddresses.Contains(ctx.Request.RemoteIpAddress)) { await next(); } }); } if (!config.DisableUserInterface) { app.UseFileServer(new FileServerOptions { RequestPath = new PathString("/assets"), FileSystem = new EmbeddedResourceFileSystem(typeof(AppBuilderExtensions).Assembly, "Thinktecture.IdentityManager.Assets") }); app.UseFileServer(new FileServerOptions { RequestPath = new PathString("/assets/libs/fonts"), FileSystem = new EmbeddedResourceFileSystem(typeof(AppBuilderExtensions).Assembly, "Thinktecture.IdentityManager.Assets.Content.fonts") }); app.UseStageMarker(PipelineStage.MapHandler); } //app.UseJsonWebToken(); SignatureConversions.AddConversions(app); var httpConfig = new HttpConfiguration(); WebApiConfig.Configure(httpConfig, config); app.UseWebApi(httpConfig); app.UseStageMarker(PipelineStage.MapHandler); }
/// <summary> /// Maps dashboard to the app builder pipeline at the specified path /// with given authorization filters that apply to any request and /// storage instance that is being used to query the information. /// </summary> /// <param name="app">The app builder</param> /// <param name="dashboardPath">The path to map dashboard</param> /// <param name="authorizationFilters">Array of authorization filters</param> /// <param name="storage">The storage instance</param> public static void MapHangfireDashboard( [NotNull] this IAppBuilder app, string dashboardPath, IEnumerable <IAuthorizationFilter> authorizationFilters, JobStorage storage) { if (app == null) { throw new ArgumentNullException("app"); } SignatureConversions.AddConversions(app); app.Map(dashboardPath, subApp => subApp.Use <DashboardMiddleware>( storage, DashboardRoutes.Routes, authorizationFilters)); }
/// <summary> /// Bootstraps Hangfire components using the given configuration /// action and maps Hangfire Dashboard to the app builder pipeline /// at the configured path ('/hangfire' by default). /// </summary> /// <param name="app">The app builder</param> /// <param name="configurationAction">Configuration action</param> public static void UseHangfire( [NotNull] this IAppBuilder app, [NotNull] Action <IBootstrapperConfiguration> configurationAction) { if (app == null) { throw new ArgumentNullException("app"); } if (configurationAction == null) { throw new ArgumentNullException("configurationAction"); } var configuration = new BootstrapperConfiguration(); configurationAction(configuration); if (configuration.Activator != null) { JobActivator.Current = configuration.Activator; } if (configuration.Storage == null) { throw new InvalidOperationException("Job storage was not configured. Please call either `UseStorage` method or its overloads."); } JobStorage.Current = configuration.Storage; foreach (var filter in configuration.Filters) { GlobalJobFilters.Filters.Add(filter); } foreach (var server in configuration.Servers) { app.RunHangfireServer(server()); } SignatureConversions.AddConversions(app); app.MapHangfireDashboard(configuration.DashboardPath, configuration.AuthorizationFilters); }
private void InitializeBuilder(StartContext context) { if (context.Builder == null) { context.Builder = _appBuilderFactory.Create(); } var addresses = new List <IDictionary <string, object> >(); foreach (string url in context.Options.Urls) { string scheme; string host; string port; string path; if (DeconstructUrl(url, out scheme, out host, out port, out path)) { addresses.Add(new Dictionary <string, object> { { Constants.Scheme, scheme }, { Constants.Host, host }, { Constants.Port, port.ToString(CultureInfo.InvariantCulture) }, { Constants.Path, path }, }); } } if (addresses.Count == 0) { int port = DeterminePort(context); addresses.Add(new Dictionary <string, object> { { Constants.Port, port.ToString(CultureInfo.InvariantCulture) }, }); } SignatureConversions.AddConversions(context.Builder); context.Builder.Properties[Constants.HostAddresses] = addresses; context.Builder.Properties[Constants.HostAppName] = context.Options.AppStartup; context.EnvironmentData.Add(new KeyValuePair <string, object>(Constants.HostAppName, context.Options.AppStartup)); }
public static IAppBuilder UseDashboard(this IAppBuilder app, string pathMatch, IDashboardOptions options, IRouteSource routeSource) { if (app == null) { throw new ArgumentNullException(nameof(app)); } if (pathMatch == null) { throw new ArgumentNullException(nameof(pathMatch)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } if (routeSource == null) { throw new ArgumentException(nameof(routeSource)); } SignatureConversions.AddConversions(app); app.Map(pathMatch, subApp => { var routes = routeSource.GetRoutes(); void TempQualifier(Func <IDictionary <string, object>, MidFunc> middleware) => subApp.Use(middleware(subApp.Properties)); if (routes == null) { throw new ArgumentNullException(nameof(routes)); } TempQualifier(_ => UseDashboard(options, routes)); }); return(app); }
public static void UseIdentityManager(this IAppBuilder app, IdentityManagerConfiguration config) { if (app == null) { throw new ArgumentNullException("app"); } if (config == null) { throw new ArgumentNullException("config"); } config.Validate(); JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>(); if (config.SecurityMode == SecurityMode.LocalMachine) { var local = new LocalAuthenticationOptions(config.AdminRoleName); app.Use <LocalAuthenticationMiddleware>(local); } else if (config.SecurityMode == SecurityMode.OAuth2) { var jwtParams = new System.IdentityModel.Tokens.TokenValidationParameters { RoleClaimType = Constants.ClaimTypes.Role, ValidAudience = config.OAuth2Configuration.Audience, ValidIssuer = config.OAuth2Configuration.Issuer, }; if (config.OAuth2Configuration.SigningCert != null) { jwtParams.IssuerSigningToken = new X509SecurityToken(config.OAuth2Configuration.SigningCert); } else { var bytes = Convert.FromBase64String(config.OAuth2Configuration.SigningKey); jwtParams.IssuerSigningToken = new BinarySecretSecurityToken(bytes); } app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions { TokenValidationParameters = jwtParams }); app.RequireScopes(new ScopeValidationOptions { AllowAnonymousAccess = true, Scopes = new string[] { config.OAuth2Configuration.Scope } }); } if (!config.DisableUserInterface) { app.UseFileServer(new FileServerOptions { RequestPath = new PathString("/assets"), FileSystem = new EmbeddedResourceFileSystem(typeof(IdentityManagerAppBuilderExtensions).Assembly, "Thinktecture.IdentityManager.Assets") }); app.UseFileServer(new FileServerOptions { RequestPath = new PathString("/assets/libs/fonts"), FileSystem = new EmbeddedResourceFileSystem(typeof(IdentityManagerAppBuilderExtensions).Assembly, "Thinktecture.IdentityManager.Assets.Content.fonts") }); app.UseStageMarker(PipelineStage.MapHandler); } SignatureConversions.AddConversions(app); var httpConfig = new HttpConfiguration(); WebApiConfig.Configure(httpConfig, config); app.UseWebApi(httpConfig); app.UseStageMarker(PipelineStage.MapHandler); }
internal static ServiceHubDispatcher PrepareAndGetDispatcher(IAppBuilder builder, HubConfiguration configuration, ServiceOptions options, string applicationName, ILoggerFactory loggerFactory) { // Ensure we have the conversions for MS.Owin so that // the app builder respects the OwinMiddleware base class SignatureConversions.AddConversions(builder); // ServiceEndpointManager needs the logger var hubs = GetAvailableHubNames(configuration); // Get the one from DI or new a default one var router = configuration.Resolver.Resolve <IEndpointRouter>() ?? new DefaultEndpointRouter(); var serverNameProvider = configuration.Resolver.Resolve <IServerNameProvider>(); if (serverNameProvider == null) { serverNameProvider = new DefaultServerNameProvider(); configuration.Resolver.Register(typeof(IServerNameProvider), () => serverNameProvider); } var endpoint = new ServiceEndpointManager(serverNameProvider, options, loggerFactory); configuration.Resolver.Register(typeof(IServiceEndpointManager), () => endpoint); var requestIdProvider = configuration.Resolver.Resolve <IConnectionRequestIdProvider>(); if (requestIdProvider == null) { requestIdProvider = new DefaultConnectionRequestIdProvider(); configuration.Resolver.Register(typeof(IConnectionRequestIdProvider), () => requestIdProvider); } builder.Use <NegotiateMiddleware>(configuration, applicationName, endpoint, router, options, serverNameProvider, requestIdProvider, loggerFactory); builder.RunSignalR(configuration); // Fetch the trace manager from DI and add logger provider var traceManager = configuration.Resolver.Resolve <ITraceManager>(); if (traceManager != null) { loggerFactory.AddProvider(new TraceManagerLoggerProvider(traceManager)); } configuration.Resolver.Register(typeof(ILoggerFactory), () => loggerFactory); // TODO: Using IOptions looks wierd, thinking of a way removing it // share the same object all through var serviceOptions = Options.Create(options); // For safety, ALWAYS register abstract classes or interfaces // Some third-party DI frameworks such as Ninject, implicit self-binding concrete types: // https://github.com/ninject/ninject/wiki/dependency-injection-with-ninject#skipping-the-type-binding-bit--implicit-self-binding-of-concrete-types configuration.Resolver.Register(typeof(IOptions <ServiceOptions>), () => serviceOptions); var serviceProtocol = new ServiceProtocol(); configuration.Resolver.Register(typeof(IServiceProtocol), () => serviceProtocol); // allow override from tests var scm = configuration.Resolver.Resolve <IServiceConnectionManager>(); if (scm == null) { scm = new ServiceConnectionManager(applicationName, hubs); configuration.Resolver.Register(typeof(IServiceConnectionManager), () => scm); } var ccm = configuration.Resolver.Resolve <IClientConnectionManager>(); if (ccm == null) { ccm = new ClientConnectionManager(configuration, loggerFactory); configuration.Resolver.Register(typeof(IClientConnectionManager), () => ccm); } var atm = new AzureTransportManager(configuration.Resolver); configuration.Resolver.Register(typeof(ITransportManager), () => atm); var parser = new SignalRMessageParser(hubs, configuration.Resolver, loggerFactory.CreateLogger <SignalRMessageParser>()); configuration.Resolver.Register(typeof(IMessageParser), () => parser); var smb = new ServiceMessageBus(configuration.Resolver, loggerFactory.CreateLogger <ServiceMessageBus>()); configuration.Resolver.Register(typeof(IMessageBus), () => smb); var scf = configuration.Resolver.Resolve <IServiceConnectionFactory>(); if (scf == null) { var connectionFactory = new ConnectionFactory(serverNameProvider, loggerFactory); scf = new ServiceConnectionFactory(serviceProtocol, ccm, connectionFactory, loggerFactory, serverNameProvider); configuration.Resolver.Register(typeof(IServiceConnectionFactory), () => scf); } var sccf = new ServiceConnectionContainerFactory(scf, endpoint, router, options, loggerFactory); if (hubs?.Count > 0) { return(new ServiceHubDispatcher(hubs, scm, sccf, serviceOptions, loggerFactory)); } else { loggerFactory.CreateLogger <DispatcherHelper>().Log(LogLevel.Warning, "No hubs found."); return(null); } }
public static void UseIdentityManager(this IAppBuilder app, IdentityManagerOptions options) { if (app == null) { throw new ArgumentNullException("app"); } if (options == null) { throw new ArgumentNullException("config"); } options.Validate(); JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>(); var container = AutofacConfig.Configure(options); app.Use <AutofacContainerMiddleware>(container); if (options.SecurityMode == SecurityMode.LocalMachine) { var local = new LocalAuthenticationOptions(options.AdminRoleName); app.Use <LocalAuthenticationMiddleware>(local); } else if (options.SecurityMode == SecurityMode.OAuth2) { var jwtParams = new System.IdentityModel.Tokens.TokenValidationParameters { NameClaimType = options.OAuth2Configuration.NameClaimType, RoleClaimType = options.OAuth2Configuration.RoleClaimType, ValidAudience = options.OAuth2Configuration.Audience, ValidIssuer = options.OAuth2Configuration.Issuer, }; if (options.OAuth2Configuration.SigningCert != null) { jwtParams.IssuerSigningToken = new X509SecurityToken(options.OAuth2Configuration.SigningCert); } else { var bytes = Convert.FromBase64String(options.OAuth2Configuration.SigningKey); jwtParams.IssuerSigningToken = new BinarySecretSecurityToken(bytes); } app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions { TokenValidationParameters = jwtParams }); app.RequireScopes(new ScopeValidationOptions { AllowAnonymousAccess = true, Scopes = new string[] { options.OAuth2Configuration.Scope } }); if (options.OAuth2Configuration.ClaimsTransformation != null) { app.Use(async(ctx, next) => { var user = ctx.Authentication.User; if (user != null) { user = options.OAuth2Configuration.ClaimsTransformation(user); ctx.Authentication.User = user; } await next(); }); } } if (!options.DisableUserInterface) { app.UseFileServer(new FileServerOptions { RequestPath = new PathString("/assets"), FileSystem = new EmbeddedResourceFileSystem(typeof(IdentityManagerAppBuilderExtensions).Assembly, "IdentityManager.Assets") }); app.UseFileServer(new FileServerOptions { RequestPath = new PathString("/assets/libs/fonts"), FileSystem = new EmbeddedResourceFileSystem(typeof(IdentityManagerAppBuilderExtensions).Assembly, "IdentityManager.Assets.Content.fonts") }); app.UseStageMarker(PipelineStage.MapHandler); } SignatureConversions.AddConversions(app); app.UseWebApi(WebApiConfig.Configure(options)); app.UseStageMarker(PipelineStage.MapHandler); }
private static IAppBuilder UseSignalRMiddleware <T>(this IAppBuilder builder, params object[] args) { ConnectionConfiguration configuration = null; // Ensure we have the conversions for MS.Owin so that // the app builder respects the OwinMiddleware base class SignatureConversions.AddConversions(builder); if (args.Length > 0) { configuration = args[args.Length - 1] as ConnectionConfiguration; if (configuration == null) { throw new ArgumentException(Resources.Error_NoConfiguration); } var resolver = configuration.Resolver; if (resolver == null) { throw new ArgumentException(Resources.Error_NoDependencyResolver); } var env = builder.Properties; CancellationToken token = env.GetShutdownToken(); // If we don't get a valid instance name then generate a random one string instanceName = env.GetAppInstanceName() ?? Guid.NewGuid().ToString(); // Use the data protection provider from app builder and fallback to the // Dpapi provider IDataProtectionProvider provider = builder.GetDataProtectionProvider(); IProtectedData protectedData; // If we're using DPAPI then fallback to the default protected data if running // on mono since it doesn't support any of this if (provider == null && MonoUtility.IsRunningMono) { protectedData = new DefaultProtectedData(); } else { if (provider == null) { provider = new DpapiDataProtectionProvider(instanceName); } protectedData = new DataProtectionProviderProtectedData(provider); } resolver.Register(typeof(IProtectedData), () => protectedData); // If the host provides trace output then add a default trace listener TextWriter traceOutput = env.GetTraceOutput(); if (traceOutput != null) { var hostTraceListener = new TextWriterTraceListener(traceOutput); var traceManager = new TraceManager(hostTraceListener); resolver.Register(typeof(ITraceManager), () => traceManager); } // Try to get the list of reference assemblies from the host IEnumerable <Assembly> referenceAssemblies = env.GetReferenceAssemblies(); if (referenceAssemblies != null) { // Use this list as the assembly locator var assemblyLocator = new EnumerableOfAssemblyLocator(referenceAssemblies); resolver.Register(typeof(IAssemblyLocator), () => assemblyLocator); } resolver.InitializeHost(instanceName, token); } builder.Use(typeof(T), args); // BUG 2306: We need to make that SignalR runs before any handlers are // mapped in the IIS pipeline so that we avoid side effects like // session being enabled. The session behavior can be // manually overridden if user calls SetSessionStateBehavior but that shouldn't // be a problem most of the time. builder.UseStageMarker(PipelineStage.PostAuthorize); return(builder); }
/// <summary> /// Extension method to configure IdentityServer in the hosting application. /// </summary> /// <param name="app">The application.</param> /// <param name="options">The <see cref="IdentityServer3.Core.Configuration.IdentityServerOptions"/>.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// app /// or /// options /// </exception> public static IAppBuilder UseIdentityServer(this IAppBuilder app, IdentityServerOptions options) { if (app == null) { throw new ArgumentNullException("app"); } if (options == null) { throw new ArgumentNullException("options"); } options.Validate(); // turn off weird claim mappings for JWTs JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>(); JwtSecurityTokenHandler.OutboundClaimTypeMap = new Dictionary <string, string>(); if (options.RequireSsl) { app.Use <RequireSslMiddleware>(); } if (options.LoggingOptions.EnableKatanaLogging) { app.SetLoggerFactory(new LibLogKatanaLoggerFactory()); } app.ConfigureRequestId(); options.ProtocolLogoutUrls.Add(Constants.RoutePaths.Oidc.EndSessionCallback); app.ConfigureDataProtectionProvider(options); app.ConfigureIdentityServerBaseUrl(options.PublicOrigin); app.ConfigureIdentityServerIssuer(options); var container = AutofacConfig.Configure(options); app.UseAutofacMiddleware(container); app.UseCors(); app.ConfigureCookieAuthentication(options.AuthenticationOptions.CookieOptions, options.DataProtector); if (options.PluginConfiguration != null) { options.PluginConfiguration(app, options); } if (options.AuthenticationOptions.IdentityProviders != null) { options.AuthenticationOptions.IdentityProviders(app, Constants.ExternalAuthenticationType); } app.UseEmbeddedFileServer(); SignatureConversions.AddConversions(app); var httpConfig = WebApiConfig.Configure(options, container); app.UseAutofacWebApi(httpConfig); app.UseWebApi(httpConfig); using (var child = container.CreateScopeWithEmptyOwinContext()) { var eventSvc = child.Resolve <IEventService>(); // TODO -- perhaps use AsyncHelper instead? DoStartupDiagnosticsAsync(options, eventSvc).Wait(); } return(app); }
/// <summary> /// Extension method to configure IdentityServer in the hosting application. /// </summary> /// <param name="app">The application.</param> /// <param name="options">The <see cref="IdentityServerOptions"/>.</param> /// <returns></returns> /// <exception cref="ArgumentNullException"> /// app /// or /// options /// </exception> public static IAppBuilder UseIdentityServer(this IAppBuilder app, IdentityServerOptions options) { if (app == null) { throw new ArgumentNullException("app"); } if (options == null) { throw new ArgumentNullException("options"); } options.Validate(); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear(); if (options.RequireSsl) { app.Use <RequireSslMiddleware>(); } if (options.LoggingOptions.EnableKatanaLogging) { app.SetLoggerFactory(new LibLogKatanaLoggerFactory()); } app.UseEmbeddedFileServer(); app.ConfigureRequestId(); app.ConfigureDataProtectionProvider(options); app.ConfigureIdentityServerBaseUrl(options.PublicOrigin); app.ConfigureIdentityServerIssuer(options); app.ConfigureRequestBodyBuffer(); // this needs to be earlier than the autofac middleware so anything is disposed and re-initialized // if we send the request back into the pipeline to render the logged out page app.ConfigureRenderLoggedOutPage(); var container = AutofacConfig.Configure(options); app.UseAutofacMiddleware(container); app.UseCors(); app.ConfigureCookieAuthentication(options.AuthenticationOptions.CookieOptions, options.DataProtector); // this needs to be before external middleware app.ConfigureSignOutMessageCookie(); if (options.PluginConfiguration != null) { options.PluginConfiguration(app, options); } if (options.AuthenticationOptions.IdentityProviders != null) { options.AuthenticationOptions.IdentityProviders(app, Constants.ExternalAuthenticationType); } app.ConfigureHttpLogging(options.LoggingOptions); SignatureConversions.AddConversions(app); var httpConfig = WebApiConfig.Configure(options, container); app.UseAutofacWebApi(httpConfig); app.UseWebApi(httpConfig); using (var child = container.CreateScopeWithEmptyOwinContext()) { var eventSvc = child.Resolve <IEventService>(); // TODO -- perhaps use AsyncHelper instead? DoStartupDiagnosticsAsync(options, eventSvc).Wait(); } return(app); }