Esempio n. 1
0
        public void Configuration(IAppBuilder app)
        {
            //var issuer = ConfigurationManager.AppSettings["jwtIssuer"];
            //var audience = ConfigurationManager.AppSettings["jwtClientId"];
            //var jwtKey = TextEncodings.Base64.Decode(ConfigurationManager.AppSettings["jwtVerificationKey"]);
            //var authOptions = new JwtBearerAuthenticationOptions
            //{
            //    AuthenticationMode = AuthenticationMode.Active,
            //    AllowedAudiences = new[] { audience },
            //    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            //    {
            //        new X509CertificateSecurityTokenProvider(issuer, new X509Certificate2(jwtKey)), 
            //    }
            //};
            //app.UseJwtBearerAuthentication(authOptions);

            var config = new HttpConfiguration();
            Bootstrapper.InstallDatabase();
            Bootstrapper.StartWith(config);

            var allowedOrigin = ConfigurationManager.AppSettings["allowOrigin"];
            if (allowedOrigin != "*")
            {
                var policy = new CorsPolicy
                {
                    AllowAnyHeader = true,
                    AllowAnyMethod = true,
                    SupportsCredentials = true,
                };

                if (allowedOrigin.EndsWith("/")) allowedOrigin = allowedOrigin.Substring(0, allowedOrigin.Length - 1);

                policy.Origins.Add(allowedOrigin);
                app.UseCors(new CorsOptions
                {
                    PolicyProvider = new CorsPolicyProvider
                    {
                        PolicyResolver = context => Task.FromResult(policy)
                    },
                    CorsEngine = new SubdomainsAcceptingCorsEngine()
                });
            }
            else
            {
                app.UseCors(CorsOptions.AllowAll);
            }
            app.UseWebApi(config);
        }
        public void ConfigureCors(IAppBuilder app)
        {
            app.Use(async (context, next) =>
            {
                var req = context.Request;
                var res = context.Response;

                if (req.Method == "OPTIONS")
                {
                    res.StatusCode = 200;
                    res.Headers.AppendCommaSeparatedValues(CorsConstants.AccessControlAllowMethods, "GET", "POST", "PUT",
                        "DELETE");

                    res.Headers.AppendCommaSeparatedValues(CorsConstants.AccessControlAllowHeaders, "accept",
                        "authorization", "content-type", "x-api-applicationid", "access-control-allow-origin", "cache-control", "x-requested-with");

                    var headerValues = req.Headers.GetValues("Origin");
                    var origin = headerValues?.FirstOrDefault();
                    if (origin != null)
                    {
                        res.Headers.Append(CorsConstants.AccessControlAllowOrigin, origin);
                    }

                    return;
                }

                await next();
            });

            app.UseCors(CorsOptions.AllowAll);
        }
Esempio n. 3
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(() => new EnergyNetworkDbContext());
              app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
              app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

              //Enable Cors support in the Web API. Should go before the activation of Bearer tokens
              //http://aspnetwebstack.codeplex.com/discussions/467315
              app.UseCors(CorsOptions.AllowAll);

              app.UseCookieAuthentication(new CookieAuthenticationOptions());

              app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

              // Enable the application to use bearer tokens to authenticate users
              // Enabling 3 components:
              // 1. Authorization Server middleware. For creating the bearer tokens
              // 2. Application bearer token middleware. Will atuthenticate every request with Authorization : Bearer header
              // 3. External bearer token middleware. For external providers
              app.UseOAuthBearerTokens(OAuthOptions);

              app.UseMicrosoftAccountAuthentication(ConfigurationManager.AppSettings["MicrosoftKey"],
            ConfigurationManager.AppSettings["MicrosoftSecret"]);

              app.UseTwitterAuthentication(ConfigurationManager.AppSettings["TwitterKey"],
            ConfigurationManager.AppSettings["TwitterSecret"]);

              app.UseFacebookAuthentication(ConfigurationManager.AppSettings["FacebookKey"],
            ConfigurationManager.AppSettings["FacebookSecret"]);

              app.UseGoogleAuthentication();
        }
        public static new void Install(HttpConfiguration config, IAppBuilder app)
        {
            config.SuppressHostPrincipal();

            app.UseCors(CorsOptions.AllowAll);

            app.MapSignalR();

            var jSettings = new JsonSerializerSettings();

            jSettings.Formatting = Formatting.Indented;

            jSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

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

            config.Formatters.JsonFormatter.SerializerSettings = jSettings;

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
Esempio n. 5
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();
            builder.RegisterInstance(GetDbExecutor(ConnectionString)).As<IDbExecutor>();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<SqlServerRepository>().As<IFeatureToggleRepository>().SingleInstance();
            builder.RegisterType<FeatureToggleValidator>().As<IFeatureToggleValidator>().SingleInstance();

            var container = builder.Build();

            app.UseCors(CorsOptions.AllowAll);
            app.UseAutofacMiddleware(container);

            var config = new HttpConfiguration();
            config.EnableSwagger(c => c.SingleApiVersion("v1", "Feature Toggle Service API"))
                  .EnableSwaggerUi();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Services.Replace(typeof(IExceptionHandler), new UnhandledErrorService());

            app.Use(typeof(AuditMiddlware));
            app.UseWebApi(config);
        }
        public static new void Install(HttpConfiguration config, IAppBuilder app)
        {
            config.SuppressHostPrincipal();

            SecurityApi.Services.Contracts.IIdentityService identityService = UnityConfiguration.GetContainer().Resolve<SecurityApi.Services.Contracts.IIdentityService>();

            app.UseOAuthAuthorizationServer(new OAuthOptions(identityService));

            app.UseJwtBearerAuthentication(new SecurityApi.Auth.JwtOptions());

            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            app.UseCors(CorsOptions.AllowAll);

            app.MapSignalR();

            var jSettings = new JsonSerializerSettings();

            jSettings.Formatting = Formatting.Indented;

            jSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

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

            config.Formatters.JsonFormatter.SerializerSettings = jSettings;

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
Esempio n. 7
0
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
            var formatters = config.Formatters;
            formatters.Remove(formatters.XmlFormatter);
            var jsonSettings = formatters.JsonFormatter.SerializerSettings;
            jsonSettings.Formatting = Formatting.Indented;
            jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(

                name: "DefaultRoute",

                routeTemplate: "api/{controller}/{id}",

                defaults: new { id = RouteParameter.Optional }

            );

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }
Esempio n. 8
0
        public void Configuration(IAppBuilder app)
        {
            //log4net.Config.XmlConfigurator.Configure();

            var bootstrapper = new Bootstrapper();
            var container = bootstrapper.Build();
            var priceFeed = container.Resolve<IPriceFeed>();
            priceFeed.Start();
            var cleaner = container.Resolve<Cleaner>();
            cleaner.Start();

            app.UseCors(CorsOptions.AllowAll);
            app.Map("/signalr", map =>
            {
                var hubConfiguration = new HubConfiguration
                {
                    // you don't want to use that in prod, just when debugging
                    EnableDetailedErrors = true,
                    EnableJSONP = true,
                    Resolver = new AutofacSignalRDependencyResolver(container)
                };

                map.UseCors(CorsOptions.AllowAll)
                    .RunSignalR(hubConfiguration);
            });
        }
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ErisSystemContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.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
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
               /// In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);
        }
Esempio n. 10
0
        public void Configuration(IAppBuilder app)
        {
            // initialize cors
            app.UseCors(CorsOptions.AllowAll);

            // initialize authentication
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                AuthenticationMode = AuthenticationMode.Active,
                ExpireTimeSpan = TimeSpan.FromHours(1),
                SlidingExpiration = true                
            });

            // initialize webapi
            HttpConfiguration config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "Default",
                routeTemplate: "{controller}/{id}",
                defaults: new 
                { 
                    id = RouteParameter.Optional 
                });

            // initialize dependency injection
            ConfigureDependencies(app, config);

            // bind web api
            app.UseWebApi(config);
        }
Esempio n. 11
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            // token consumption
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            var container = SimpleInjectorConfig.Register();
            var config = new HttpConfiguration
            {
                DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container)
            };
            WebApiConfig.Register(config);
            app.UseWebApi(config);

            Func<IUserService> userServiceFactory = () => container.GetInstance<IUserService>();
            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                // for demo purposes
                AllowInsecureHttp = true,

                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),

                Provider = new AuthorizationServerProvider(userServiceFactory)
            });
        }
Esempio n. 12
0
        public void Configuration(IAppBuilder app)
        {
           
            // token validation
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = Constants.IdentityServerUri,
                RequiredScopes = new[] { "apiAccess" }
            });

            // add app local claims per request
            app.UseClaimsTransformation(incoming =>
            {
                // either add claims to incoming, or create new principal
                var appPrincipal = new ClaimsPrincipal(incoming);
                incoming.Identities.First().AddClaim(new Claim("appSpecific", "some_value"));

                return Task.FromResult(appPrincipal);
            });

            app.UseCors(CorsOptions.AllowAll);

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            // web api configuration
            app.UseWebApi(config);
        }
Esempio n. 13
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);
            app.RunSignalR();

            XmlConfigurator.Configure();
        }
Esempio n. 14
0
 // This method is required by Katana:
 public void Configuration(IAppBuilder app)
 {
     var webApiConfiguration = ConfigureWebApi();
     
     app.UseCors(CorsOptions.AllowAll);            
     app.UseWebApi(webApiConfiguration);
 }
            private static void UseWebApi(IAppBuilder application, IKernel kernel)
            {
                var config = new HttpConfiguration();
                config.MapHttpAttributeRoutes();
                var cors = new EnableCorsAttribute("*", "*", "*");

                //GlobalConfiguration.Configure(configuration =>
                //{
                //    configuration.SuppressDefaultHostAuthentication();
                //    configuration.MapHttpAttributeRoutes();
                //    configuration.EnableCors(cors);
                //    configuration.Filters.Add(new HostAuthenticationAttribute(OAuthDefaults.AuthenticationType));
                //    var jsonformatter = configuration.Formatters.JsonFormatter;
                //    jsonformatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                //    configuration.AddJsonpFormatter();
                //    application.UseNinjectMiddleware(() => kernel);
                //    application.UseNinjectWebApi(configuration);
                //    application.UseWebApi(configuration);
                //});
                config.SuppressDefaultHostAuthentication();
                ConfigureOAuth(application);
                config.EnableCors(cors);
                config.Filters.Add(new HostAuthenticationAttribute(OAuthDefaults.AuthenticationType));
                var jsonformatter = config.Formatters.JsonFormatter;
                jsonformatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                config.AddJsonpFormatter();

                application.UseNinjectMiddleware(() => kernel);
                application.UseNinjectWebApi(config);
                application.UseWebApi(config);

                application.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            }
Esempio n. 16
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);

            ConfigureAuth(app);
            app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(GlobalConfiguration.Configuration);
        }
Esempio n. 17
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            try
            {
                app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

                // 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
                //app.UseCookieAuthentication(new CookieAuthenticationOptions());
                //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

                // Enable the application to use bearer tokens to authenticate users
                app.UseOAuthBearerTokens(OAuthOptions);

                // 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();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
Esempio n. 18
0
 public void Configuration(IAppBuilder app)
 {
     var configuration = new HubConfiguration();
     configuration.EnableDetailedErrors = true;
     app.UseCors(CorsOptions.AllowAll);
     app.MapSignalR(configuration);
 }
Esempio n. 19
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);

            ConfigureAuth(app);
            GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
        }
Esempio n. 20
0
        public void ConfigureAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AuthenticationType = Constant.GrantTypes.AuthenticationType,
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString(WebConfig.TokenPath),
                AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(int.Parse(WebConfig.AccessTokenExpireTimeSpan)),
                Provider = new OAuth2AuthorizationServerProvider(),
                RefreshTokenProvider = new OAuth2RefreshTokenProvider()
            };
            //AuthenticationType :认证类型
            //AllowInsecureHttp : 如果允许客户端的 return_uri 参数不是 HTTPS 地址, 则设置为 true
            //TokenEndpointPath : 客户端应用可以直接访问并得到访问令牌的地址, 必须以前倒斜杠 "/" 开始, 例如: /Token
            //AccessTokenExpireTimeSpan :Token过期时间
            //Provider : 应用程序提供和 OAuth 认证中间件交互的 IOAuthAuthorizationServerProvider 实例, 通常可以使用默认的
            //OAuthAuthorizationServerProvider , 并设置委托函数即可
            //RefreshTokenProvider :刷新令牌, 如果这个属性没有设置, 则不能从 /Token 刷新令牌

            // 令牌生成
            app.UseOAuthAuthorizationServer(OAuthServerOptions);

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            //跨域处理
            app.UseCors(CorsOptions.AllowAll);
        }
Esempio n. 21
0
        public static void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var OAuthOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/oauth/Token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),
                Provider = new Providers.MyAuthorizationServerProvider(),
                // RefreshTokenProvider = new Providers.MyRefreshTokenProvider(DateTime.UtcNow.AddHours(8))
            };
            app.UseOAuthAuthorizationServer(OAuthOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            // We don't need this crap anymore!
            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);

            app.UseWebApi(config);
        }
Esempio n. 22
0
 public void Configuration(IAppBuilder app)
 {
     ConfigureAuth(app);
     ConfigureWebApi(app);
     ConfigureNancy(app);
     app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
 }
Esempio n. 23
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            ConfigureAuth(app);

            var config = new HttpConfiguration();

            config.DependencyResolver = new NinjectResolver((new Bootstrapper()).Kernel);

            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var formatters = config.Formatters;
            var jsonFormatter = formatters.JsonFormatter;
            var settings = jsonFormatter.SerializerSettings;
            settings.Formatting = Formatting.Indented;
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            app.UseWebApi(config);
        }
Esempio n. 24
0
        public void Configuration(IAppBuilder app)
        {
            // This must come first to intercept the /Token requests
            app.UseCors(CorsOptions.AllowAll);

            ConfigureAuth(app);
        }
Esempio n. 25
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);

            HttpConfiguration httpConfig = new HttpConfiguration();

            ConfigureOAuthTokenGeneration(app);

            // Configure Log4net logger
            var log4NetSettings = new FileInfo(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase.Replace("bin", "Config"), "Log4Net.xml"));
            log4net.Config.XmlConfigurator.Configure(log4NetSettings);

            // Configure HTTP Logging feature
            app.UseHttpLogging(new HttpLoggingOptions
            {
                TrackingStore = new HttpLoggingStore(),
                TrackingIdPropertyName = "x-tracking-id",
                MaximumRecordedRequestLength = 64 * 1024,
                MaximumRecordedResponseLength = 64 * 1024
            });

            ConfigureWebAPI(httpConfig);

            app.UseWebApi(httpConfig);
        }
 private void Configuration(IAppBuilder builder)
 {
     var httpConfiguration = GetHttpConfiguration();
     builder.UseCors(CorsOptions.AllowAll);
     builder.UseWindsorDependencyResolverScope(httpConfiguration, container);
     builder.UseWebApi(httpConfiguration);
 }
Esempio n. 27
0
		public void Configuration(IAppBuilder app)
		{

			app.UseCors(CorsOptions.AllowAll);

			InitializeAutoMapper ();

			// Rest API Setup
			var config = new HttpConfiguration(); 

			config.MapHttpAttributeRoutes ();

			// Use only JSON by default.
			var xmlFormatterSupportedMediaTypes = config.Formatters.XmlFormatter.SupportedMediaTypes;
			var appXmlType = xmlFormatterSupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
			xmlFormatterSupportedMediaTypes.Remove(appXmlType);

			config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

			config.Filters.Add(new ExceptionHandlerFilter(config.Formatters.JsonFormatter));

			app.UseWebApi(config);

			app.MapSignalR <Echo>("/test");

		}
Esempio n. 28
0
        public void Configuration(IAppBuilder app)
        {
            var policy = new CorsPolicy
            {
                AllowAnyHeader = true,
                AllowAnyMethod = true,
                SupportsCredentials = true
            };

            policy.ExposedHeaders.Add("Authorization");

            app.UseCors(new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(policy)
                }
            });

            var config = new HttpConfiguration();

            WebApiConfig.Register(config);

            app.UseNinjectMiddleware(CreateKernel);
            app.UseNinjectWebApi(config);

        }
Esempio n. 29
0
        public void Configuration(IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();

            appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            ContainerBuilder containerBuilder = new ContainerBuilder();

            containerBuilder.RegisterModule<HostingModule>();

            containerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            var container = containerBuilder.Build();
            
            var resolver = new AutofacWebApiDependencyResolver(container);
            config.DependencyResolver = resolver;

            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());
            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            config.MapHttpAttributeRoutes();

            appBuilder.UseAutofacMiddleware(container);
            appBuilder.UseAutofacWebApi(config);
            appBuilder.UseWebApi(config);
        }
Esempio n. 30
0
        public void Configuration(IAppBuilder app)
        {
            app.Map("/signalr", map =>
            {
                app.UseCors(CorsOptions.AllowAll);

                var hubConfiguration = new HubConfiguration
                {
                    EnableJSONP = true
                };
                
                /*
                GlobalHost.DependencyResolver.UseSqlServer(
                        "Data Source=(local);"+
                        "Initial Catalog=SignalRChat;"+
                        "Integrated Security=True"
                    );

                GlobalHost.DependencyResolver.UseRedis(
                    "localhost",
                    6379,
                    "",
                    "signalr.key");

                GlobalHost.DependencyResolver.UseServiceBus(
                    "your connection string from azure",
                    "signalr");
                 */

                map.RunSignalR(hubConfiguration);
            });
        }
Esempio n. 31
0
 public void Configuration(IAppBuilder app)
 {
     app.UseCors(CorsOptions.AllowAll);
     _dashboard.Configuration(app);
 }
Esempio n. 32
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            ConfigureAuth(app);
        }
Esempio n. 33
0
 // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
 public void ConfigureAuth(IAppBuilder app)
 {
     app.UseCors(CorsOptions.AllowAll);
 }
Esempio n. 34
0
 public static void Configuration(IAppBuilder app)
 {
     app.UseCors(CorsOptions.AllowAll)
     .MapSignalR <PingConnection>("/ping-connection")
     .MapSignalR("/hub", new HubConfiguration());
 }
Esempio n. 35
0
        public static void Configure(IAppBuilder app, IUnityContainer container)
        {
            app.CreatePerOwinContext(() => container.Resolve <SecurityDbContext>());
            app.CreatePerOwinContext(() => container.Resolve <ApplicationUserManager>());

            var origins = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:CORS:AllowedOrigins");

            if (!string.IsNullOrEmpty(origins))
            {
                var corsPolicy = new CorsPolicy
                {
                    AllowAnyMethod = true,
                    AllowAnyHeader = true
                };

                var originsArray = origins.Split(';');
                if (originsArray.Contains("*"))
                {
                    corsPolicy.AllowAnyOrigin = true;
                }
                else
                {
                    foreach (var origin in originsArray)
                    {
                        corsPolicy.Origins.Add(origin);
                    }
                }

                var corsOptions = new CorsOptions
                {
                    PolicyProvider = new CorsPolicyProvider
                    {
                        PolicyResolver = context => Task.FromResult(corsPolicy)
                    }
                };

                app.UseCors(corsOptions);
            }


            var authenticationOptions = container.Resolve <AuthenticationOptions>();

            if (authenticationOptions.CookiesEnabled)
            {
                // 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
                {
                    AuthenticationMode = authenticationOptions.AuthenticationMode,
                    AuthenticationType = authenticationOptions.AuthenticationType,
                    CookieDomain       = authenticationOptions.CookieDomain,
                    CookieHttpOnly     = authenticationOptions.CookieHttpOnly,
                    CookieName         = authenticationOptions.CookieName,
                    CookiePath         = authenticationOptions.CookiePath,
                    CookieSecure       = authenticationOptions.CookieSecure,
                    ExpireTimeSpan     = authenticationOptions.ExpireTimeSpan,
                    LoginPath          = authenticationOptions.LoginPath,
                    LogoutPath         = authenticationOptions.LogoutPath,
                    ReturnUrlParameter = authenticationOptions.ReturnUrlParameter,
                    SlidingExpiration  = authenticationOptions.SlidingExpiration,
                    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: authenticationOptions.CookiesValidateInterval,
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, authenticationOptions.AuthenticationType))
                    }
                });
            }

            if (authenticationOptions.BearerTokensEnabled)
            {
                container.RegisterType <IRefreshTokenService, RefreshTokenService>();

                var refreshTokenService  = container.Resolve <IRefreshTokenService>();
                var refreshTokenProvider = new RefreshTokenProvider(authenticationOptions.RefreshTokenExpireTimeSpan, refreshTokenService);
                var eventPublisher       = container.Resolve <IEventPublisher>();
                var securityService      = container.Resolve <ISecurityService>();

                app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
                {
                    TokenEndpointPath     = new PathString("/Token"),
                    AuthorizeEndpointPath = new PathString("/Account/Authorize"),
                    Provider                  = new ApplicationOAuthProvider(PublicClientId, authenticationOptions, eventPublisher, securityService),
                    RefreshTokenProvider      = refreshTokenProvider,
                    AccessTokenExpireTimeSpan = authenticationOptions.AccessTokenExpireTimeSpan,
                    AllowInsecureHttp         = true
                });
            }

            if (authenticationOptions.HmacEnabled || authenticationOptions.ApiKeysEnabled)
            {
                var apiAccountProvider     = container.Resolve <IApiAccountProvider>();
                var claimsIdentityProvider = container.Resolve <IClaimsIdentityProvider>();
                var cacheManager           = container.Resolve <ICacheManager <object> >();


                if (authenticationOptions.HmacEnabled)
                {
                    app.UseHmacAuthentication(new HmacAuthenticationOptions
                    {
                        ApiCredentialsProvider  = apiAccountProvider,
                        IdentityProvider        = claimsIdentityProvider,
                        CacheManager            = cacheManager,
                        SignatureValidityPeriod = authenticationOptions.HmacSignatureValidityPeriod
                    });
                }

                if (authenticationOptions.ApiKeysEnabled)
                {
                    app.UseApiKeysAuthentication(new ApiKeysAuthenticationOptions
                    {
                        ApiCredentialsProvider   = apiAccountProvider,
                        IdentityProvider         = claimsIdentityProvider,
                        CacheManager             = cacheManager,
                        HttpHeaderName           = authenticationOptions.ApiKeysHttpHeaderName,
                        QueryStringParameterName = authenticationOptions.ApiKeysQueryStringParameterName
                    });
                }
            }

            if (authenticationOptions.AzureAdAuthenticationEnabled)
            {
                // Cookie authentication to temporarily store external authentication data.
                // NOTE: AuthenticationType should not change - it is used internally by ASP.NET external authentication code!
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                    AuthenticationMode = AuthenticationMode.Passive
                });

                var authority = authenticationOptions.AzureAdInstance + authenticationOptions.AzureAdTenantId;
                app.UseOpenIdConnectAuthentication(
                    new OpenIdConnectAuthenticationOptions
                {
                    AuthenticationType         = authenticationOptions.AzureAdAuthenticationType,
                    Caption                    = authenticationOptions.AzureAdAuthenticationCaption,
                    ClientId                   = authenticationOptions.AzureAdApplicationId,
                    Authority                  = authority,
                    AuthenticationMode         = AuthenticationMode.Passive,
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
                });
            }

            app.Use <CurrentUserOwinMiddleware>(container.Resolve <Func <ICurrentUser> >());
        }
Esempio n. 36
0
        public void Configuration(IAppBuilder Builder)
        {
            ConfigureOAuth(Builder);

            var Configuration = new HttpConfiguration();
            var HTTPServer    = new HttpServer(Configuration);

            #region Custom Routing and WebAPI versionong
            Builder.UseWebApi(Configuration);

            // reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions"
            Configuration.AddApiVersioning(O => O.ReportApiVersions = true);



            Configuration.Routes.MapHttpRoute(
                "VersionedUrl",
                "api/{namespace}/{application}/v{apiVersion}/{module}/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { apiVersion = new ApiVersionRouteConstraint() });
            Configuration.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{namespace}/{application}/v{apiVersion}/{module}/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { apiVersion = new ApiVersionRouteConstraint() });
            Configuration.Routes.MapHttpRoute(
                "VersionedNoAppUrl",
                "api/{namespace}/v{apiVersion}/{module}/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { apiVersion = new ApiVersionRouteConstraint() });
            Configuration.Routes.MapHttpRoute(
                "DefaultApiNoApp",
                "api/{namespace}/v{apiVersion}/{module}/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: new { apiVersion = new ApiVersionRouteConstraint() });
            Configuration.Routes.MapHttpRoute(
                "VersionedQueryString",
                "api/{namespace}/{application}/{module}/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });
            Configuration.Routes.MapHttpRoute(
                "VersionedQueryStringWithAction",
                "api/{namespace}/{application}/{module}/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional });



            Configuration.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(Configuration));
            #endregion

            #region Register DBContext, Service, Repository To Unity
            var Container = new UnityContainer();

            Container.RegisterType <BookDBMSSQLIDBFactory, BookDBMSSQLDBFactory>(new HierarchicalLifetimeManager());
            //Container.RegisterType<BookDBMongoDBIDBFactory, BookDBMongoDBDBFactory>(new HierarchicalLifetimeManager());


            //Container.RegisterType<BookDBOracleIDBFactory, BookDBOracleDBFactory>(new HierarchicalLifetimeManager());

            Container.RegisterTypes(
                AllClasses.FromAssemblies(typeof(BookDBRepository).Assembly)
                .Where(t => t.Name.EndsWith("Repository")),
                WithMappings.FromAllInterfaces);
            // Container.RegisterType<IRolesRepository, RolesRepository>(new InjectionConstructor("DeveloperCompetencyDBEntities"));

            Container.RegisterTypes(
                AllClasses.FromAssemblies(typeof(BookDBService).Assembly)
                .Where(t => t.Name.EndsWith("Service")),
                WithMappings.FromAllInterfaces);

            Configuration.DependencyResolver = new UnityResolver(Container);
            #endregion

            //MongoDB Datetime Converter
            BsonSerializer.RegisterSerializer(typeof(DateTime), DateTimeSerializer.UtcInstance);

            //Allow Cross Domain Access
            Builder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            Builder.UseWebApi(HTTPServer);
        }
Esempio n. 37
0
        // For more information on configuring authentication, please visit https://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);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            // 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);

            // 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);


            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.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
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions   = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/Token"),
                Provider                  = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath     = new PathString("/api/AccountApi/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // 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 void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);

            string contentPath = Path.Combine(Environment.CurrentDirectory, @"..\..");

            app.UseStaticFiles(contentPath);
            loginForm = File.ReadAllBytes(Path.Combine(contentPath, @"Account/form.html"));

            var options = new CookieAuthenticationOptions()
            {
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                LoginPath          = CookieAuthenticationDefaults.LoginPath,
                LogoutPath         = CookieAuthenticationDefaults.LogoutPath,
            };

            app.UseCookieAuthentication(options);

            app.Use(async(context, next) =>
            {
                var redirectUri = context.Request.Query["ReturnUrl"];

                if (context.Request.Path.Value.Contains(options.LoginPath.Value))
                {
                    if (context.Request.Method == "POST")
                    {
                        var form     = await context.Request.ReadFormAsync();
                        var userName = form["UserName"];
                        var password = form["Password"];

                        if (!ValidateUserCredentials(userName, password))
                        {
                            var redirect = options.LoginPath.Value;
                            if (!String.IsNullOrEmpty(redirectUri))
                            {
                                redirect += "?ReturnUrl=" + WebUtility.UrlEncode(redirectUri);
                            }

                            context.Response.Redirect(redirect);
                        }

                        var identity = new ClaimsIdentity(options.AuthenticationType);
                        identity.AddClaim(new Claim(ClaimTypes.Name, userName));
                        context.Authentication.SignIn(identity);

                        redirectUri = redirectUri ?? "/index.html";
                        context.Response.Redirect(redirectUri);
                    }
                    else
                    {
                        context.Response.ContentType = "text/html";
                        await context.Response.WriteAsync(loginForm);
                    }
                }
                else if (context.Request.Path.Value.Contains(options.LogoutPath.Value))
                {
                    context.Authentication.SignOut(options.AuthenticationType);
                    redirectUri = redirectUri ?? options.LoginPath.Value;
                    context.Response.Redirect(redirectUri);
                }
                else if (context.Request.User == null || !context.Request.User.Identity.IsAuthenticated)
                {
                    context.Response.Redirect(options.LoginPath.Value);
                }
                else if (context.Request.Path.Value == "/")
                {
                    context.Response.Redirect("/index.html");
                }
                else
                {
                    await next();
                }
            });

            app.MapSignalR <AuthorizeEchoConnection>("/echo");
            app.MapSignalR();
        }
Esempio n. 39
0
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888

            //log4net 加载配置
            XmlConfigurator.Configure();

            var config = new HttpConfiguration();

            //注册对象映射
            Mintcode.TuoTuo.v2.AutoMapper.Configuration.Configure();

            //属性路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            FluentValidationConfig.ConfigureContainer(config);

            //autofac
            var builder = new ContainerBuilder();

            //日志
            builder.Register(c => LogManager.GetLogger("GlobalLog")).Keyed("GlobalLog", typeof(ILog));
            builder.Register(c => LogManager.GetLogger("ExceptionLog")).Keyed("ExceptionLog", typeof(ILog));
            //filter
            //builder.RegisterType<GlobalAuthenticationFilter>().AsWebApiAuthenticationFilterFor<BaseController>().InstancePerRequest();
            builder.RegisterType <GlobalActionFilter>().AsWebApiActionFilterFor <BaseController>().InstancePerRequest();
            builder.RegisterType <GlobalValidateErrorFilter>().AsWebApiActionFilterFor <BaseController>().InstancePerRequest();
            builder.RegisterType <GlobalExceptionFilter>().WithAttributeFiltering().AsWebApiExceptionFilterFor <BaseController>().InstancePerRequest();
            //logic
            builder.RegisterType <UserRepository>().As <IUserRepository>().InstancePerLifetimeScope();
            builder.RegisterType <ProjectRepository>().As <IProjectRepository>().InstancePerLifetimeScope();
            builder.RegisterType <TeamRepository>().As <ITeamRepository>().InstancePerLifetimeScope();
            builder.RegisterType <TimeSheetRepository>().As <ITimeSheetRepository>().InstancePerLifetimeScope();
            builder.RegisterType <TaskRepository>().As <ITaskRepository>().InstancePerLifetimeScope();
            builder.RegisterType <RefreshTokenRepository>().As <IRefreshTokenRepository>().InstancePerLifetimeScope();
            builder.RegisterType <RelationAccountRepository>().As <IRelationAccountRepository>().InstancePerLifetimeScope();
            builder.RegisterType <AttachmentUploadRepository>().As <IAttachmentUploadRepository>().InstancePerLifetimeScope();
            builder.RegisterType <BacklogRepository>().As <IBacklogRepository>()
            .OnActivated(s => s.Instance.SetTaskRepository(s.Context.Resolve <ITaskRepository>())).InstancePerLifetimeScope();
            builder.RegisterType <ScrumRepository>().As <IScrumRepository>()
            .OnActivated(s => s.Instance.SetBacklogRepository(s.Context.Resolve <IBacklogRepository>())).InstancePerLifetimeScope();
            //BLL
            var assembly = Assembly.Load("Mintcode.TuoTuo.v2.BLL");

            builder.RegisterAssemblyTypes(assembly).Where(t =>
                                                          t.BaseType.GetGenericTypeDefinition().Equals(typeof(BLLBase <>)));
            //api
            builder.RegisterApiControllers(Assembly.Load("Mintcode.TuoTuo.v2.Webapi")).WithAttributeFiltering();
            builder.RegisterWebApiFilterProvider(config);

            //redis
            builder.Register(c =>
            {
                var redisConfig               = ConfigurationManager.ConnectionStrings["redis"].ConnectionString;
                var options                   = ConfigurationOptions.Parse(redisConfig);
                options.AbortOnConnectFail    = false;
                var connection                = ConnectionMultiplexer.Connect(options);
                connection.PreserveAsyncOrder = false;
                return(connection);
            }).AsSelf().SingleInstance();

            builder.Register(c => c.Resolve <ConnectionMultiplexer>().GetDatabase()).As <IDatabase>();

            //OAuth 逻辑
            builder.RegisterType <OpenRefreshTokenProvider>();
            builder.RegisterType <SimpleAuthorizationServerProvider>();
            builder.Register((c, p) => new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(int.Parse(ConfigurationManager.AppSettings["AccessTokenExpireDay"])),

                AccessTokenFormat = new TicketDataFormat(app.CreateDataProtector(
                                                             typeof(OAuthAuthorizationServerMiddleware).Namespace,
                                                             "Access_Token", "v1")),
                Provider = c.Resolve <SimpleAuthorizationServerProvider>(),

                RefreshTokenFormat = new TicketDataFormat(app.CreateDataProtector(
                                                              typeof(OAuthAuthorizationServerMiddleware).Namespace,
                                                              "Refresh_Token", "v1")),
                RefreshTokenProvider = c.Resolve <OpenRefreshTokenProvider>()
            }).SingleInstance();
            builder.RegisterType <IdentityService>()
            .OnActivated(s => s.Instance.options = s.Context.Resolve <OAuthAuthorizationServerOptions>());

            //Api Handlers
            builder.RegisterType <CASOAuthHandler>().OnActivating(e =>
            {
                e.Instance.SetIdentityService(e.Context.Resolve <IdentityService>());
                e.Instance.SetUserRepository(e.Context.Resolve <IUserRepository>());
                e.Instance.SetRelationAccountRepository(e.Context.Resolve <IRelationAccountRepository>());
            });

            //Email
            #region 废弃代码
            //builder.Register(c => {
            //    var mailConfig = ConfigurationManager.GetSection("mailConfig") as MailConfigurationSection;
            //    return mailConfig;
            //}).AsSelf().SingleInstance();
            //builder.Register(async (c, p) =>
            //{
            //    try
            //    {
            //        var mailConfig = c.Resolve<MailConfigurationSection>();
            //        var smtpClient = new MailKit.Net.Smtp.SmtpClient();

            //        smtpClient.AuthenticationMechanisms.Remove("XOAUTH2");

            //        int port = int.Parse(mailConfig.Port.Text);
            //        await smtpClient.ConnectAsync(mailConfig.Server.Text, port, mailConfig.EnableSsl.Text.Equals("true"));
            //        await smtpClient.AuthenticateAsync(mailConfig.UserName.Text, mailConfig.Password.Text);

            //        return smtpClient;
            //    }
            //    catch (Exception ex)
            //    {
            //        return null;
            //    }

            //}).AsSelf().SingleInstance();
            //builder.Register((c, p) =>
            //{
            //    var smtpClient = new MailKit.Net.Smtp.SmtpClient();
            //    smtpClient.AuthenticationMechanisms.Remove("XOAUTH2");
            //    return smtpClient;
            //}).AsSelf().SingleInstance();
            #endregion
            builder.Register(c =>
            {
                var mailConfig = ConfigurationManager.GetSection("mailConfig") as TuoTuoMailConfigurationSection;
                return(mailConfig);
            }).AsSelf().SingleInstance();
            builder.RegisterType <EmailService>().As <IEmailService>();

            //加密
            builder.RegisterType <JWTTokenSecurity>().As <ITokenSecurity>();


            //Validator
            builder.RegisterModule <ValidatorModule>();

            //文件
            builder.RegisterType <LocalFileService>().As <IFileService>();

            //模板
            builder.Register(c =>
            {
                var templateConfig = new TemplateServiceConfiguration();
                templateConfig.DisableTempFileLocking = true;
                templateConfig.CachingProvider        = new DefaultCachingProvider(t => { });
                return(RazorEngineService.Create(templateConfig));
            }).AsSelf().SingleInstance();
            builder.RegisterType <TemplateHelper>().SingleInstance();

            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            app.UseCors(CorsOptions.AllowAll);

            app.UseAutofacMiddleware(container);

            app.UseAutofacWebApi(config);

            //OAuth 配置
            app.UseOAuthAuthorizationServer(container.Resolve <OAuthAuthorizationServerOptions>());
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            app.UseWebApi(config);



            //第三方认证路由
            config.Routes.MapHttpRoute(
                name: "CAS OAuth",
                routeTemplate: "cas",
                defaults: null,
                constraints: null,
                handler: container.Resolve <CASOAuthHandler>()
                );
        }
Esempio n. 40
0
        public static void BuildWithContainer(IAppBuilder app, Container container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            Config = new HttpConfiguration();
            ExceptionlessClient.Default.RegisterWebApi(Config);

            Log.Info().Message("Starting api...").Write();
            // if enabled, auto upgrade the database
            if (Settings.Current.ShouldAutoUpgradeDatabase)
            {
                var    url          = new MongoUrl(Settings.Current.MongoConnectionString);
                string databaseName = url.DatabaseName;
                if (Settings.Current.AppendMachineNameToDatabase)
                {
                    databaseName += String.Concat("-", Environment.MachineName.ToLower());
                }

                MongoMigrationChecker.EnsureLatest(Settings.Current.MongoConnectionString, databaseName);
            }

            Config.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger());
            Config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
            Config.Formatters.Remove(Config.Formatters.XmlFormatter);
            Config.Formatters.JsonFormatter.SerializerSettings.Formatting       = Formatting.Indented;
            Config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new LowerCaseUnderscorePropertyNamesContractResolver();

            var constraintResolver = new DefaultInlineConstraintResolver();

            constraintResolver.ConstraintMap.Add("objectid", typeof(ObjectIdRouteConstraint));
            constraintResolver.ConstraintMap.Add("objectids", typeof(ObjectIdsRouteConstraint));
            constraintResolver.ConstraintMap.Add("token", typeof(TokenRouteConstraint));
            constraintResolver.ConstraintMap.Add("tokens", typeof(TokensRouteConstraint));
            Config.MapHttpAttributeRoutes(constraintResolver);
            //Config.EnableSystemDiagnosticsTracing();

            container.RegisterSingle <JsonSerializer>(JsonSerializer.Create(new JsonSerializerSettings {
                ContractResolver = new SignalRContractResolver()
            }));
            container.RegisterWebApiFilterProvider(Config);

            try {
                container.Verify();
            } catch (Exception ex) {
                var tempEx = ex;
                while (!(tempEx is ReflectionTypeLoadException))
                {
                    if (tempEx.InnerException == null)
                    {
                        break;
                    }
                    tempEx = tempEx.InnerException;
                }

                var typeLoadException = tempEx as ReflectionTypeLoadException;
                if (typeLoadException != null)
                {
                    foreach (var loaderEx in typeLoadException.LoaderExceptions)
                    {
                        Debug.WriteLine(loaderEx.Message);
                    }
                }

                Debug.WriteLine(ex.Message);
                throw;
            }

            Config.MessageHandlers.Add(container.GetInstance <XHttpMethodOverrideDelegatingHandler>());
            Config.MessageHandlers.Add(container.GetInstance <EncodingDelegatingHandler>());
            Config.MessageHandlers.Add(container.GetInstance <AuthMessageHandler>());

            // Throttle api calls to X every 15 minutes by IP address.
            Config.MessageHandlers.Add(container.GetInstance <ThrottlingHandler>());

            // Reject event posts in orgs over their max event limits.
            Config.MessageHandlers.Add(container.GetInstance <OverageHandler>());

            app.UseCors(new CorsOptions {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = ctx => Task.FromResult(new CorsPolicy
                    {
                        AllowAnyHeader      = true,
                        AllowAnyMethod      = true,
                        AllowAnyOrigin      = true,
                        SupportsCredentials = true,
                        PreflightMaxAge     = 60 * 5
                    })
                }
            });

            app.CreatePerContext <Lazy <User> >("User", ctx => new Lazy <User>(() => {
                if (ctx.Request.User == null || ctx.Request.User.Identity == null || !ctx.Request.User.Identity.IsAuthenticated)
                {
                    return(null);
                }

                string userId = ctx.Request.User.GetUserId();
                if (String.IsNullOrEmpty(userId))
                {
                    return(null);
                }

                var userRepository = container.GetInstance <IUserRepository>();
                return(userRepository.GetById(userId, true));
            }));

            app.CreatePerContext <Lazy <Project> >("DefaultProject", ctx => new Lazy <Project>(() => {
                if (ctx.Request.User == null || ctx.Request.User.Identity == null || !ctx.Request.User.Identity.IsAuthenticated)
                {
                    return(null);
                }

                // TODO: Use project id from url. E.G., /projects/{projectId:objectid}/events
                string projectId      = ctx.Request.User.GetDefaultProjectId();
                var projectRepository = container.GetInstance <IProjectRepository>();

                if (String.IsNullOrEmpty(projectId))
                {
                    var firstOrgId = ctx.Request.User.GetOrganizationIds().FirstOrDefault();
                    if (!String.IsNullOrEmpty(firstOrgId))
                    {
                        var project = projectRepository.GetByOrganizationId(firstOrgId, useCache: true).FirstOrDefault();
                        if (project != null)
                        {
                            return(project);
                        }
                    }

                    if (Settings.Current.WebsiteMode == WebsiteMode.Dev)
                    {
                        var dataHelper = container.GetInstance <DataHelper>();
                        // create a default org and project
                        projectId = dataHelper.CreateDefaultOrganizationAndProject(ctx.Request.GetUser());
                    }
                }

                if (String.IsNullOrEmpty(projectId))
                {
                    return(null);
                }

                return(projectRepository.GetById(projectId, true));
            }));

            app.UseWebApi(Config);
            var resolver = new SimpleInjectorSignalRDependencyResolver(container);

            if (Settings.Current.EnableRedis)
            {
                resolver.UseRedis(new RedisScaleoutConfiguration(Settings.Current.RedisConnectionString, "exceptionless.signalr"));
            }
            app.MapSignalR("/api/v2/push", new HubConfiguration {
                Resolver = resolver
            });

            Mapper.Configuration.ConstructServicesUsing(container.GetInstance);

            var context = new OwinContext(app.Properties);
            var token   = context.Get <CancellationToken>("host.OnAppDisposing");

            CreateSampleData(container);

            if (Settings.Current.RunJobsInProcess)
            {
                Task.Factory.StartNew(() => container.GetInstance <EventPostsJob>().RunContinuousAsync(token: token), token, TaskCreationOptions.LongRunning, TaskScheduler.Default).IgnoreExceptions();
                Task.Factory.StartNew(() => container.GetInstance <EventUserDescriptionsJob>().RunContinuousAsync(token: token), token, TaskCreationOptions.LongRunning, TaskScheduler.Default).IgnoreExceptions();
                Task.Factory.StartNew(() => container.GetInstance <MailMessageJob>().RunContinuousAsync(token: token), token, TaskCreationOptions.LongRunning, TaskScheduler.Default).IgnoreExceptions();
                Task.Factory.StartNew(() => container.GetInstance <EventNotificationsJob>().RunContinuousAsync(token: token), token, TaskCreationOptions.LongRunning, TaskScheduler.Default).IgnoreExceptions();
                Task.Factory.StartNew(() => container.GetInstance <WebHooksJob>().RunContinuousAsync(token: token), token, TaskCreationOptions.LongRunning, TaskScheduler.Default).IgnoreExceptions();
                //Task.Factory.StartNew(() => container.GetInstance<DailySummaryJob>().RunContinuousAsync(delay: TimeSpan.FromMinutes(15), token: token), token, TaskCreationOptions.LongRunning, TaskScheduler.Default).IgnoreExceptions();
                //Task.Factory.StartNew(() => container.GetInstance<RetentionLimitsJob>().RunContinuousAsync(delay: TimeSpan.FromHours(8), token: token), token, TaskCreationOptions.LongRunning, TaskScheduler.Default).IgnoreExceptions();
                //Task.Factory.StartNew(() => container.GetInstance<StaleAccountsJob>().RunContinuousAsync(delay: TimeSpan.FromHours(8), token: token), token, TaskCreationOptions.LongRunning, TaskScheduler.Default).IgnoreExceptions();
            }
        }
Esempio n. 41
0
 public void Configuration(IAppBuilder app)
 {
     app.UseCors(CorsOptions.AllowAll);
     app.MapSignalR();
 }
Esempio n. 42
0
        public void Configuration(IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();

            // enable windows auth credentials
#if !DEBUG_NO_AUTH
            var owinHttp = appBuilder.Properties["Microsoft.Owin.Host.HttpListener.OwinHttpListener"] as Microsoft.Owin.Host.HttpListener.OwinHttpListener;
            owinHttp.Listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
#endif

#if DEBUG
            config
            .EnableSwagger(c => c.SingleApiVersion("v1", "Service API for local install of Certify SSL Manager"))
            .EnableSwaggerUi();
#endif

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            appBuilder.MapSignalR("/api/status", new HubConfiguration());
            appBuilder.UseWebApi(config);

            _container = new ServiceContainer();

            _container.RegisterApiControllers();
            _container.EnableWebApi(config);

            // inject single CertifyManager for service to use
            _container.Register <Management.ICertifyManager, Management.CertifyManager>(new PerContainerLifetime());

            var currentCertifyManager = _container.GetInstance <Management.ICertifyManager>();

            // attached handlers for SignalR hub updates
            currentCertifyManager.OnRequestProgressStateUpdated += (Models.RequestProgressState obj) =>
            {
                // notify client(s) of status updates
                StatusHub.SendRequestProgressState(obj);
            };

            currentCertifyManager.OnManagedCertificateUpdated += (Models.ManagedCertificate obj) =>
            {
                // notify client(s) of update to a managed site
                StatusHub.SendManagedCertificateUpdate(obj);
            };

            // hourly jobs timer (renewal etc)
            _timer          = new System.Timers.Timer(60 * 60 * 1000); // every 60 minutes
            _timer.Elapsed += _timer_Elapsed;
            _timer.Start();

            // daily jobs timer ((cleanup etc)
            _dailyTimer          = new System.Timers.Timer(24 * 60 * 60 * 1000); // every 24 hrs
            _dailyTimer.Elapsed += _dailyTimer_Elapsed;
            _dailyTimer.Start();
        }
Esempio n. 43
0
 public void Configuration(IAppBuilder app)
 {
     app.UseCors(CorsOptions.AllowAll);
     ConfigureAuth(app);
     app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(GlobalConfiguration.Configuration);
 }
Esempio n. 44
0
 public void Configuration(IAppBuilder app)
 {
     // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
     app.UseCors(CorsOptions.AllowAll);
 }
Esempio n. 45
0
 public void Configuration(IAppBuilder app)
 {
     app.UseCors(CorsOptions.AllowAll)
     .UseStaticFiles(new StaticFileOptions())
     .MapSignalR();
 }
Esempio n. 46
0
        /// <summary>
        /// Configuration.
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            // Load the configuration
            IConfigurationService configurationService = new JsonConfigurationService($"{Environment.CurrentDirectory}/config.json");

            string hangfireConnectionString = ConfigurationManager.ConnectionStrings["Hangfire"].ConnectionString;

            Log.Information("Hangfire connection string {hangfireConnection}", hangfireConnectionString);


            // Autofac API container
            var apiContainerBuilder = new ContainerBuilder();

            apiContainerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            apiContainerBuilder.RegisterType <SendDocumentsJob>();
            apiContainerBuilder.RegisterType <StoreAndForwardDbContext>().AsSelf()
            .OnActivating(d => Log.Information("OnActivating - StoreAndForwardDbContext"))
            .OnRelease(d =>     // Uses Autofac automatic disposal for the DB context
            {
                Log.Information("OnRelease - StoreAndForwardDbContext");
                d.Dispose();
            });

            apiContainerBuilder.RegisterType <QueueManager>().As <IQueueManager>()
            .WithParameter("retryLimit", configurationService.RetryLimit);
            apiContainerBuilder.RegisterType <DataStore>().As <IDataStore>();
            apiContainerBuilder.RegisterType <SignalrNotificationService>().As <INotificationService>();
            apiContainerBuilder.RegisterType <CdaPackageService>().As <ICdaPackageService>();
            apiContainerBuilder.RegisterType <MhrDocumentUploadClient>().As <IMhrDocumentUploadClient>();
            apiContainerBuilder.RegisterType <MhrDocumentUploadClient>().As <IMhrDocumentUploadClient>()
            .WithParameter("endpoint", configurationService.UploadDocumentEndpoint)
            .WithParameter("certificate", configurationService.Certificate)
            .WithParameter("facilityType", configurationService.HealthcareFacility)
            .WithParameter("practiceSetting", configurationService.PracticeSetting)
            .WithParameter("clientSystem", configurationService.ClientSystemType)
            .WithParameter("productInfo", configurationService.ProductInfo);

            // HTTP configuration
            var httpConfiguration = new HttpConfiguration();

            httpConfiguration.MapHttpAttributeRoutes();
            httpConfiguration.Formatters.Remove(httpConfiguration.Formatters.XmlFormatter);
            httpConfiguration.Formatters.Add(httpConfiguration.Formatters.JsonFormatter);
            httpConfiguration.Services.Replace(typeof(IExceptionHandler), new StoreAndForwardExceptionHandler());

            //config.EnableSystemDiagnosticsTracing();
            SystemDiagnosticsTraceWriter diagnosticsTraceWriter = new SystemDiagnosticsTraceWriter
            {
                MinimumLevel = TraceLevel.Off,
                IsVerbose    = true
            };

            httpConfiguration.Services.Replace(typeof(ITraceWriter), (object)diagnosticsTraceWriter);
            httpConfiguration.MessageHandlers.Add(new SerilogLoggingMessageHandler());

            // OpenAPI
            httpConfiguration.EnableSwagger(c =>
            {
                c.SingleApiVersion("v1", "Store and Forward API");
                c.IncludeXmlComments(GetXmlCommentsPath());
                c.RootUrl(r => $"{r.RequestUri.Scheme}://{r.RequestUri.Authority}/storeandforward");
            })
            .EnableSwaggerUi(c =>
            {
                c.DisableValidator();     // Prevent Swashbuckle using external validation
            });

            var apiContainer = apiContainerBuilder.Build();

            httpConfiguration.DependencyResolver = new AutofacWebApiDependencyResolver(apiContainer);

            // Hangfire setup
            GlobalConfiguration.Configuration
            .UseSqlServerStorage(hangfireConnectionString)
            .UseAutofacActivator(apiContainer);

            // Setup CORS
            var corsPolicy = new CorsPolicy
            {
                AllowAnyMethod      = true,
                AllowAnyHeader      = true,
                AllowAnyOrigin      = true,
                SupportsCredentials = false
            };

            var corsOptions = new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(corsPolicy)
                }
            };

            app.UseCors(corsOptions);

            // Add SignalR
            app.MapSignalR();

            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                // Allow all IPs to connect
                Authorization = new[] { new DebugHangfireDashboardAuthorizationFilter() }
            });
            app.UseHangfireServer();

            // Web API
            app.UseAutofacMiddleware(apiContainer);
            app.UseAutofacWebApi(httpConfiguration);
            app.UseWebApi(httpConfiguration);

            // Create a recurring job
            RecurringJob.AddOrUpdate <SendDocumentsJob>(c => c.Execute(), Cron.MinuteInterval(configurationService.SendIntervalInMinutes));
        }
Esempio n. 47
0
        //public void ConfigureServices(IServiceCollection services)
        //{
        //   services.AddMemoryCache();
        //   //services.AddMvc();
        //}

        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            app.CreatePerOwinContext <AppIdentityDbContext>(AppIdentityDbContext.Create);
            app.CreatePerOwinContext <AppUserManager>(AppUserManager.Create);

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/api/tap/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1.1),
                Provider = new SimpleAuthorizationServerProvider(AppIdentityDbContext.Create)
            };

            // Token Generation

            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
                Provider = new OAuthBearerAuthenticationProvider()
            });

            WebApiConfig.Register(config);

            app.UseWebApi(config);

            // MVC Authentication

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/account/login"),
                ExpireTimeSpan     = TimeSpan.FromDays(30),
                SlidingExpiration  = true
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            app.UseSteamAuthentication(System.Configuration.ConfigurationManager.AppSettings["steamAPIKey"]);

            Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("AppIdentityDbContext");
            var auth = new Hangfire.Dashboard.AuthorizationFilter()
            {
                Users = "Monukai", Roles = "Admin"
            };

            //var options = new BackgroundJobServerOptions { WorkerCount = 1 };
            app.UseHangfireDashboard("/hangfire", new DashboardOptions {
                Authorization = new[] { new HangfireAuthorizationFilter()
                                        {
                                            Roles = new List <String> {
                                                "Admin"
                                            }
                                        } }
            });

            app.UseHangfireServer();

            TaskRegister.RegisterAuctions();
            TaskRegister.RegisterGiveaways();
            TaskRegister.RegisterDailyTasks();
        }
Esempio n. 48
0
        public void Configuration(IAppBuilder app)
        {
            // In OWIN you create your own HttpConfiguration rather than
            // re-using the GlobalConfiguration.
            var config = new HttpConfiguration();

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var cors = new EnableCorsAttribute("*", "*", "*");

            config.EnableCors(cors);

            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());
            config.Formatters.JsonFormatter.SerializerSettings =
                new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{controller}/{action}/{id}",
                new { id = RouteParameter.Optional });
            //config.Routes.MapHttpRoute(
            //    "DefaultActionApi",
            //    "{controller}/{action}/{id}",
            //    new { id = RouteParameter.Optional });

            var builder = new ContainerBuilder();

            // Register Web API controller in executing assembly.
            builder.RegisterApiControllers(GetType().Assembly).PropertiesAutowired();

            //注册 ApplicationService
            builder.RegisterAssemblyTypes(GetType().Assembly)
            .Where(type => typeof(BaseDao).IsAssignableFrom(type))
            .AsSelf().PropertiesAutowired()
            .InstancePerRequest();

            //注册数据库对象
            builder.Register <IDapperConnection>(ctx => new DapperConnection(new MySqlConnection("server=localhost;port=3306;user id=root; password=lyx123456; database=studyplan; pooling=true; charset=utf8mb4"))).InstancePerRequest();

            // Create and assign a dependency resolver for Web API to use.
            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            DependencyResolver = config.DependencyResolver;

            // The Autofac middleware should be the first middleware added to the IAppBuilder.
            // If you "UseAutofacMiddleware" then all of the middleware in the container
            // will be injected into the pipeline right after the Autofac lifetime scope
            // is created/injected.
            //
            // Alternatively, you can control when container-based
            // middleware is used by using "UseAutofacLifetimeScopeInjector" along with
            // "UseMiddlewareFromContainer". As long as the lifetime scope injector
            // comes first, everything is good.
            app.UseAutofacMiddleware(container);

            // Again, the alternative to "UseAutofacMiddleware" is something like this:
            // app.UseAutofacLifetimeScopeInjector(container);
            //app.UseMiddlewareFromContainer<FirstMiddleware>();
            //app.UseMiddlewareFromContainer<ContextMiddleware>();

            // Make sure the Autofac lifetime scope is passed to Web API.

            app.UseAutofacWebApi(config);
            app.UseWebApi(config);

            app.UseStaticFile(new StaticFileMiddlewareOptions
            {
                RootDirectory           = "../web",
                DefaultFile             = "index.html",
                EnableETag              = true,
                EnableHtml5LocationMode = true
            });
        }
Esempio n. 49
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            app.MapSignalR();
        }
Esempio n. 50
0
 public void Configuration(IAppBuilder app)
 {
     app.UseCors(CorsOptions.AllowAll);
     AtivarAcessoToken(app);
 }
Esempio n. 51
0
 public void Configuration(IAppBuilder app)
 {
     app.UseCors(CorsOptions.AllowAll); // cross-domain support
     app.MapSignalR();
 }
 public static void Configuration(IAppBuilder app)
 {
     app.UseWelcomePage("/");
     app.UseCors(CorsOptions.AllowAll);
     app.MapSignalR();
 }
Esempio n. 53
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder app)
        {
            try
            {
                var httpConfig = new HttpConfiguration();

                var config = StartupHelper.Configuration;
                // var funnyQuotesConfig = new FunnyQuotesConfiguration();

                // config.GetSection("FunnyQuotes").Bind(funnyQuotesConfig);

                // -- container registration
                var builder = new ContainerBuilder();    // build up autofac container
                builder.RegisterOptions();               // allow injection of strongly typed config
                builder.RegisterOption <FunnyQuotesConfiguration>(config.GetSection("FunnyQuotes"));
                builder.RegisterDiscoveryClient(config); // register eureka service discovery
                builder.RegisterConfiguration(config);
                builder.RegisterCloudFoundryOptions(config);
                builder.RegisterMySqlConnection(config);
                builder.RegisterConsoleLogging();
                builder.Register(ctx => // register EF context
                {
                    var connString = ctx.Resolve <IDbConnection>().ConnectionString;
                    return(new FunnyQuotesCookieDbContext(connString));
                });
                builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // register all controllers to be injectable
                builder.RegisterWebApiFilterProvider(httpConfig);                // register autofac support for webapi filters
                builder.RegisterType <LoggerExceptionFilterAttribute>()          // register global exception handler
                .AsWebApiExceptionFilterFor <ApiController>()
                .SingleInstance();
                builder.RegisterCloudFoundryActuators(config);

                var container = builder.Build(); // compile the container

                // -- configure owin server
                httpConfig.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); // default to json instead of xml
                httpConfig.Routes.MapHttpRoute(                                                                     // setup default routing for WebApi2
                    "DefaultApi",
                    "api/{controller}/{action}"
                    );
                httpConfig.Routes.MapHttpRoute("Health",
                                               "{controller}/{action}",
                                               new { controller = "health", action = "health" }); // map "/" to basic health endpoint so the default PCF health check for HTTP 200 response is satisfied
                httpConfig.DependencyResolver = new AutofacWebApiDependencyResolver(container);   // assign autofac to provide dependency injection on controllers
                var funnyQuotesConfig = container.Resolve <IOptionsMonitor <FunnyQuotesConfiguration> >().CurrentValue;

                // -- setup app pipeline
                app.UseAutofacMiddleware(container); // allows injection of dependencies into owin middleware
                if (funnyQuotesConfig.EnableSecurity)
                {
                    app.UseCloudFoundryJwtBearerAuthentication(config); // add security integration for PCF SSO
                }
                else
                {
                    app.Use <NoAuthenticationMiddleware>(); // dummy security provider which is necessary if you have secured actions on controllers
                }
                app.UseAutofacWebApi(httpConfig);           // merges owin pipeline with autofac request lifecycle
                app.UseWebApi(httpConfig);                  // standard OWIN WebAPI2
                app.UseCors(CorsOptions.AllowAll);
                container.StartDiscoveryClient();           // ensure that discovery client is started
                ContainerBuilderExtensions.StartActuators(container);
                var logger = container.Resolve <ILogger <Startup> >();

                container.MigrateDatabase();

                logger.LogInformation(">> App Started <<");
            }
            catch (Exception e)
            {
                // given that logging is DI controlled it may not be initialized, just write directly to console
                Console.Error.WriteLine(e);
                throw;
            }
        }
Esempio n. 54
0
 public void Configuration(IAppBuilder app)
 {
     app.UseCors(CorsOptions.AllowAll);
     ConfigureAuth(app);
     WebApiConfig.Register(app);
 }
Esempio n. 55
0
 public void Configuration(IAppBuilder app)
 {
     app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); // New code line to enable cors
     ConfigureAuth(app);
 }
Esempio n. 56
0
 private void ConfigureCors(IAppBuilder builder)
 {
     builder.UseCors(CorsOptions.AllowAll);
 }
Esempio n. 57
0
 public void Configuration(IAppBuilder app)
 {
     ConfigureAuth(app);
     app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
     app.MapSignalR(); //dodali smo nakon sto smo instalirali SignalR
 }
Esempio n. 58
0
 public void Configuration(IAppBuilder app)
 {
     app.UseCors(CorsOptions.AllowAll);
     app.MapSignalR("/signalchat", new HubConfiguration());
 }
        /// <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();

            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);
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);

            app.UseOAuthBearerTokens(OAuthOptions);
        }