Example #1
0
        public void Configuration(IAppBuilder app)
        {
            app.UseHealthCheck("/health", new HealthCheckMiddlewareConfig());

            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
            app.UseAesDataProtectorProvider(_startupModel.EncryptionPassword);

#if !DEBUG
            var redisHost = _startupModel.Host.Split(' ')[0];
            var redis     = new RedisScaleoutConfiguration(redisHost, _startupModel.EventAppName);
            GlobalHost.DependencyResolver.UseRedis(redis);
#endif

            GlobalHost.DependencyResolver.Register(typeof(QrCodeHub), () => new QrCodeHub());
            app.Map("/signalr", map =>
            {
                //ref: https://forums.asp.net/t/2033309.aspx?Calling+SignalR+hub+from+other+domain+via+CORS
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration()
                {
                    //EnableJSONP = true,
                    EnableDetailedErrors = true,
                    //EnableJavaScriptProxies = true
                };

                map.RunSignalR(hubConfiguration);
            });
        }
Example #2
0
        private void MapSignalR(IAppBuilder app, ILifetimeScope scope)
        {
            if (_configuration.EnableOnPremiseConnections == ModuleBinding.False)
            {
                return;
            }

            const string path = "/signalr";

            GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(_configuration.ConnectionTimeout);
            GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(_configuration.DisconnectTimeout);
            GlobalHost.Configuration.KeepAlive         = TimeSpan.FromSeconds(_configuration.KeepAliveInterval);

            var sharedSecret = _configuration.SharedSecret;

            if (!String.IsNullOrWhiteSpace(sharedSecret))
            {
                app.UseAesDataProtectorProvider(sharedSecret);
            }

            if (_configuration.EnableOnPremiseConnections == ModuleBinding.Local)
            {
                app.Use(typeof(BlockNonLocalRequestsMiddleware), path);
            }

            app.MapSignalR <OnPremisesConnection>(path, new ConnectionConfiguration
            {
                Resolver = new AutofacDependencyResolver(scope),
            });
        }
Example #3
0
        public void Configuration(IAppBuilder app)
        {
            LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider());
            Log.Logger = new LoggerConfiguration()
               .MinimumLevel.Debug()
               .WriteTo.Trace()
               .CreateLogger();

            app.UseAesDataProtectorProvider();
            app.Map("/admin", adminApp =>
                {
                    var factory = new IdentityManagerServiceFactory();
                   
                    factory.ConfigureSimpleIdentityManagerService("AspId");
                    //factory.ConfigureCustomIdentityManagerServiceWithIntKeys("AspId_CustomPK");

                    var adminOptions = new IdentityManagerOptions(){
                        Factory = factory
                    };
                    adminOptions.SecurityConfiguration.RequireSsl = false;
                    adminApp.UseIdentityManager(adminOptions);
                });

            var idSvrFactory = Factory.Configure();
            idSvrFactory.ConfigureUserService("AspId");

            var viewOptions = new ViewServiceOptions
            {
                TemplatePath = this.basePath.TrimEnd(new char[] { '/' })
            };
            idSvrFactory.ViewService = new IdentityServer3.Core.Configuration.Registration<IViewService>(new ViewService(viewOptions));

            var options = new IdentityServerOptions
            {
                SiteName = "IdentityServer3 - ViewSerive-AspNetIdentity",
                SigningCertificate = Certificate.Get(),
                Factory = idSvrFactory,
                RequireSsl = false,
                AuthenticationOptions = new AuthenticationOptions
                {
                    IdentityProviders = ConfigureAdditionalIdentityProviders,
                }
            };

            app.Map("/core", core =>
            {
                core.UseIdentityServer(options);
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath = new PathString("/Content"),
                FileSystem = new PhysicalFileSystem(Path.Combine(this.basePath, "Content")) 
            });

            var config = new HttpConfiguration();
          //  config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("API", "api/{controller}/{action}", new { controller = "Home", action = "Get" });
            app.UseWebApi(config);
        }
Example #4
0
        public static void Configure(IAppBuilder app)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Trace()
                         .CreateLogger();
            app.UseAesDataProtectorProvider();

            BasePath = AppDomain.CurrentDomain.BaseDirectory;
            var certFile = Path.Combine(BasePath, "idsrv3test.pfx");

            Console.WriteLine(certFile);
            var options = ConfigureIdentityServer(certFile);

            //  var cpath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),"..", "..", "..", "src", "Janitor", "Content"));
            //  Console.WriteLine(cpath);
            //  app.UseStaticFiles (new StaticFileOptions {
            //		RequestPath = new PathString("/Content"),
            //		FileSystem = new PhysicalFileSystem(cpath)
            //	});

            app.Map("/admin", adminApp =>
            {
                var factory = new IdentityManagerServiceFactory();
                factory.ConfigureSimpleIdentityManagerService("AspId");
                var adminOptions = new IdentityManagerOptions
                {
                    Factory = factory,
                };
                adminOptions.SecurityConfiguration.RequireSsl = false;
                adminApp.UseIdentityManager(adminOptions);
            });

            app.UseIdentityServer(options);
        }
Example #5
0
        void ConfigureWebApiAuthentication(IAppBuilder builder, IContainer container)
        {
            builder.UseCookieAuthentication(new CookieAuthenticationOptions {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
            });

            builder.UseAesDataProtectorProvider();
        }
Example #6
0
        public void Configuration(IAppBuilder appBuilder)
        {
            var logger            = (ILogger)_options.DependencyResolver.GetService(typeof(ILogger));
            var permissionService =
                (IPermissionService)_options.DependencyResolver.GetService(typeof(IPermissionService));

            var http = new HttpConfiguration();

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

            http.SuppressDefaultHostAuthentication();
            http.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
            http.Filters.Add(new AuthorizeFilter(logger, permissionService, _options.PermissionedApplications));

            http.Formatters.Clear();
            http.Formatters.Add(new JsonNetFormatter());
            http.DependencyResolver = _options.DependencyResolver;
            http.Services.Replace(typeof(IExceptionHandler), new LoggingExceptionHandler(logger));


            GlobalHost.Configuration.DisconnectTimeout        = _options.SignalRConnectionTimeout;
            GlobalHost.Configuration.DefaultMessageBufferSize = _options.SignalRBufferSize;

            var serverOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/oauth/token"),
                Provider                  = new NtlmOAuthAuthorizationServerProvider(),
                AccessTokenExpireTimeSpan = _options.DefaultTokenExpiry,
                AllowInsecureHttp         = true
            };

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active
            };

            if (_options.AllowTokenAsUrlParameter)
            {
                bearerOptions.Provider = new CustomOAuthBearerAuthenticationProvider("api_key");
            }

            appBuilder.UseCors(CorsOptions.AllowAll);
            appBuilder.UseOAuthAuthorizationServer(serverOptions);
            appBuilder.UseAesDataProtectorProvider();
            appBuilder.UseOAuthBearerAuthentication(bearerOptions);
            appBuilder.UseWebApi(http);

            var listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];

            listener.AuthenticationSchemeSelectorDelegate = AuthenticationSchemeSelectorDelegate;

            SwaggerConfig.Register(http);
        }
Example #7
0
        void ConfigureCookieAuthentication(IAppBuilder builder)
        {
            builder.UseCookieAuthentication(new CookieAuthenticationOptions {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString(RouteConfiguration.GetMvcLoginPath()),
                ReturnUrlParameter = "returnUrl",
            });

            builder.UseAesDataProtectorProvider();
        }
Example #8
0
        private static void ConfigureOwinServices(IAppBuilder app)
        {
            GlobalHost.DependencyResolver.Register(typeof(IAssemblyLocator), () => new SignalRAssemblyLocator());
            app.Properties["host.AppName"] = "AbpZeroTemplate";

            app.UseAbp();
            app.UseAesDataProtectorProvider();

            app.MapSignalR();
        }
Example #9
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login")
            });

            app.UseAesDataProtectorProvider();
        }
        public override void Configure([NotNull] IAppBuilder appBuilder)
        {
            appBuilder.UseAesDataProtectorProvider();

            appBuilder.UseContentTypeMappingMiddleware(
                new RequestMap
            {
                {
                    (new PathString(TokenEndpoint), "POST", "application/json"),
                    async owinContext =>
                    await(owinContext?.ConvertFromJsonToFormBody() ??
                          throw new InvalidOperationException(@"Task is null"))
                }
            }
Example #11
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            // DpapiDataProtector is not supported on Linux/OSX
            // Use UseAesDataProtector instead
            app.UseAesDataProtectorProvider();

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
                {
                    Provider = new SolitudeAuthorizationServerProvider(),
                    AllowInsecureHttp = true,
                    TokenEndpointPath = new PathString("/api/token"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                };

            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
        private static void ConfigureSignalR(IAppBuilder app)
        {
            app.UseAesDataProtectorProvider(SignalRScaleoutConfiguration.EncryptionPassword);

            if (SignalRScaleoutConfiguration.UseScaleout)
            {
                var redisConfig = new RedisScaleoutConfiguration(
                    SignalRScaleoutConfiguration.RedisConnectionString,
                    SignalRScaleoutConfiguration.RedisAppName);
                GlobalHost.DependencyResolver.UseRedis(redisConfig);
            }

            var configuration = new HubConfiguration {
                EnableDetailedErrors = true
            };

            app.MapSignalR(configuration);
        }
Example #13
0
        public void Configuration(IAppBuilder app)
        {
            //If I put this here or after UseCookieAuthentication I always get 2 cookies in the response
            app.UseMyMiddleware();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                CookieHttpOnly     = true,
                CookieSecure       = Microsoft.Owin.Security.Cookies.CookieSecureOption.SameAsRequest,
                SlidingExpiration  = true,
                AuthenticationType = "MyCookie",
            });

            app.UseNancy();

            app.UseAesDataProtectorProvider();
        }
Example #14
0
        public void Configuration(IAppBuilder appBuilder)
        {
            appBuilder.UseAesDataProtectorProvider();
            var factory = new IdentityServerServiceFactory();
            factory
                .UseInMemoryClients(Clients.Get())
                .UseInMemoryScopes(Scopes.Get())
                .UseInMemoryUsers(Users.Get());

            var options = new IdentityServerOptions
            {
                SiteName = "IdentityServer3 (self host)",

                SigningCertificate = Certificate.Get(),
                Factory = factory,
                RequireSsl = false
            };
            appBuilder.UseIdentityServer(options);
        }
        private static void ConfigureOwinServices(IAppBuilder app)
        {
            GlobalHost.DependencyResolver.Register(typeof(IAssemblyLocator), () => new SignalRAssemblyLocator());
            app.Properties["host.AppName"] = "DOTIC";

            app.UseAbp();
            app.UseAesDataProtectorProvider();

            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);

                var hubConfiguration = new HubConfiguration
                {
                    EnableJSONP = true
                };

                map.RunSignalR(hubConfiguration);
            });
        }
Example #16
0
        public void Configuration(IAppBuilder app)
        {
            LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider());
            Log.Logger = new LoggerConfiguration()
               .MinimumLevel.Debug()
               .WriteTo.Trace()
               .CreateLogger();

            app.UseAesDataProtectorProvider();
            app.Map("/admin", adminApp =>
                {
                    var factory = new IdentityManagerServiceFactory();

                    factory.ConfigureSimpleIdentityManagerService("AspId");
                    //factory.ConfigureCustomIdentityManagerServiceWithIntKeys("AspId_CustomPK");

                    var adminOptions = new IdentityManagerOptions(){
                        Factory = factory
                    };
                    adminOptions.SecurityConfiguration.RequireSsl = false;
                    adminApp.UseIdentityManager(adminOptions);
                });

            var idSvrFactory = Factory.Configure();
            idSvrFactory.ConfigureUserService("AspId");
            //idSvrFactory.ConfigureCustomUserService("AspId_CustomPK");

            var options = new IdentityServerOptions
            {
                SiteName = "IdentityServer3 - UserService-AspNetIdentity",
                SigningCertificate = Certificate.Get(),
                Factory = idSvrFactory,
                RequireSsl = false,
                AuthenticationOptions = new AuthenticationOptions
                {
                    IdentityProviders = ConfigureAdditionalIdentityProviders,
                }
            };

            app.UseIdentityServer(options);
        }
Example #17
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            if (RuntimeHelper.IsRunningOnMono())
            {
                appBuilder.UseAesDataProtectorProvider();
            }
            var config = new HttpConfiguration();


            var corsPolicy = new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE");

            // Cors for the Asp.Net Identity (OAuth handler)
            appBuilder.UseCors(new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = request =>
                                     request.Path.Value == "/token" ?
                                     corsPolicy.GetCorsPolicyAsync(null, CancellationToken.None) :
                                     Task.FromResult <CorsPolicy>(null)
                }
            });

            // Cors for the WebApi
            config.EnableCors(corsPolicy);



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


            var jsonFormatter = config.Formatters.OfType <JsonMediaTypeFormatter>().First();

            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            jsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;

            appBuilder.UseWebApi(config);
        }
Example #18
0
        public void Configuration(IAppBuilder app)
        {
            // Exclude AcspNet from exclude assemblies to be able to load example controllers
            AcspTypesFinder.ExcludedAssembliesPrefixes.Remove("AcspNet");

            var provider = new SimpleInjectorDIProvider();
            DIContainer.Current = provider;

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/login")
            });

            app.UseAesDataProtectorProvider();

            app.UseAcspNet();

            provider.Container.Verify();

            AcspNetOwinMiddleware.OnException += Ex;
        }
Example #19
0
        public void Configuration(IAppBuilder app)
        {
            // Exclude AcspNet from exclude assemblies to be able to load example controllers
            AcspTypesFinder.ExcludedAssembliesPrefixes.Remove("AcspNet");

            var provider = new SimpleInjectorDIProvider();

            DIContainer.Current = provider;

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/login")
            });

            app.UseAesDataProtectorProvider();

            app.UseAcspNet();

            provider.Container.Verify();

            AcspNetOwinMiddleware.OnException += Ex;
        }
Example #20
0
        public static void OAuthConfiguration(IAppBuilder appBuilder, IAuthManager authManager,
                                              bool allowInsecureHttp             = true,
                                              string tokenEndpointPath           = "/token",
                                              TimeSpan?accessTokenExpireTimeSpan = null)
        {
            var oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = allowInsecureHttp,
                TokenEndpointPath         = new PathString(tokenEndpointPath),
                AccessTokenExpireTimeSpan = accessTokenExpireTimeSpan ?? TimeSpan.FromDays(1),
                Provider = new OAuthAuthorizationServerProvider(authManager),
            };


            var oAuthBearerOptions = new OAuthBearerAuthenticationOptions()
            {
                Provider = new OAuthBearerAuthenticationProvider()
            };

            // Token Generation
            appBuilder.UseOAuthAuthorizationServer(oAuthServerOptions);
            appBuilder.UseOAuthBearerAuthentication(oAuthBearerOptions);
            appBuilder.UseAesDataProtectorProvider();
        }
Example #21
0
        public static void Configure(IAppBuilder app)
        {
            Log.Logger = new LoggerConfiguration()
                       .MinimumLevel.Debug()
                       .WriteTo.Trace()
                       .CreateLogger();
            app.UseAesDataProtectorProvider();

            BasePath = AppDomain.CurrentDomain.BaseDirectory;
            var certFile = Path.Combine(BasePath, "idsrv3test.pfx");
            Console.WriteLine(certFile);
            var options = ConfigureIdentityServer(certFile);

            //  var cpath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),"..", "..", "..", "src", "Janitor", "Content"));
            //  Console.WriteLine(cpath);
            //  app.UseStaticFiles (new StaticFileOptions {
            //		RequestPath = new PathString("/Content"),
            //		FileSystem = new PhysicalFileSystem(cpath)
            //	});

            app.Map("/admin", adminApp =>
            {
                var factory = new IdentityManagerServiceFactory();
                factory.ConfigureSimpleIdentityManagerService("AspId");
                    var adminOptions = new IdentityManagerOptions
                        {
                            Factory = factory,

                        };
                    adminOptions.SecurityConfiguration.RequireSsl = false;
                    adminApp.UseIdentityManager(adminOptions);
            });

            app.UseIdentityServer(options);
        }
Example #22
0
 public void Configuration(IAppBuilder app)
 {
     ConfigureAuth(app);
     app.UseAesDataProtectorProvider();
     app.MapSignalR();
 }
Example #23
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.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);

            int expiryInDays = int.Parse(ConfigurationManager.AppSettings["TokenExpiryInDays"]);

            // 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(expiryInDays),
                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: "");

            FacebookAuthOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions
            {
                AppId     = ConfigurationManager.AppSettings["FacebookAppId"].ToString(),
                AppSecret = ConfigurationManager.AppSettings["FacebookAppSecret"].ToString(),
                // NOTE: gseng - may need to use a backchannel handler to retrieve email, first_name and etc
                // BackchannelHttpHandler = new FacebookBackChannelHandler(),
                // UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name,location",
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                Scope    = { "email" },
                Provider = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        await System.Threading.Tasks.Task.Run(() =>
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                            foreach (var claim in context.User)
                            {
                                var claimType     = string.Format("urn:facebook:{0}", claim.Key);
                                string claimValue = claim.Value.ToString();
                                if (!context.Identity.HasClaim(claimType, claimValue))
                                {
                                    context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
                                }
                            }
                        });
                    }
                }
            };

            app.UseFacebookAuthentication(FacebookAuthOptions);

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});

            app.UseAesDataProtectorProvider();
        }
Example #24
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            if (RuntimeHelper.IsRunningOnMono())
            {
                appBuilder.UseAesDataProtectorProvider();
            }
            var config = new HttpConfiguration();

            config.DependencyResolver = new UnityDependencyResolver(_unityContainer);
            config.Filters.Add(new SessionExceptionHandlerFilterAttribute());
            config.Filters.Add(_unityContainer.Resolve <GlobalExceptionHandlerFilterAttribute>());



            var corsPolicy = new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE");

            // Cors for the Asp.Net Identity (OAuth handler)
            appBuilder.UseCors(new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = request =>
                                     request.Path.Value == "/token" ?
                                     corsPolicy.GetCorsPolicyAsync(null, CancellationToken.None) :
                                     Task.FromResult <CorsPolicy>(null)
                }
            });

            // Cors for the WebApi
            config.EnableCors(corsPolicy);



            var aumf =
                (ApplicationUserManagerFacotory)
                config.DependencyResolver.GetService(typeof(ApplicationUserManagerFacotory));

            // Configure the db context and user manager to use a single instance per request
            // app.CreatePerOwinContext(ApplicationDbContext.Create);
            appBuilder.CreatePerOwinContext <ApplicationUserManager>(
                (options, context) => { return((ApplicationUserManager)aumf.Create(options, context)); });

            var OAuthServerOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),

                Provider =
                    new CustomOAuthProvider("GameApi",
                                            (ISessionManagerClientFactory)
                                            config.DependencyResolver.GetService(typeof(ISessionManagerClientFactory)))
            };


            // Token Generation
            appBuilder.UseOAuthAuthorizationServer(OAuthServerOptions)
            .UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());


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


            var jsonFormatter = config.Formatters.OfType <JsonMediaTypeFormatter>().First();

            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            jsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;

            appBuilder.UseWebApi(config);
        }
Example #25
0
        public void Configuration(IAppBuilder app)
        {
            var requireSSL = false;
            var idserverendpoint = "/identity";
            var serverReplyUrl = Path.Combine(baseUrl, idserverendpoint);

            // Publish the internal idserver to authenticate users
            app.Map(idserverendpoint, idServer => idServer.UseIdentityServer(
                    new IdentityServerOptions
                    {
                        SiteName = "MySite",
                        //SigningCertificate = CertificateLoader.LoadCertificate(_idServerSigningCertificateThumbprint),
                        Factory = GetFactory(),
                        RequireSsl = requireSSL,
                        PublicOrigin = baseUrl,
                        CspOptions = new CspOptions{ Enabled = false },
                        AuthenticationOptions = new AuthenticationOptions
                        {
                            CookieOptions = new CookieOptions
                            {
                                SecureMode = requireSSL ? CookieSecureMode.Always : CookieSecureMode.SameAsRequest
                            },
                            EnableLocalLogin = true,
                            EnableSignOutPrompt = false,
                            EnablePostSignOutAutoRedirect = false,
                            IdentityProviders = ConfigureIdentityProviders
                        }
                    }));

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

            // Use the internal idserver for authentication
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                {
                    Authority = serverReplyUrl,
                    ClientId = "myawesomeclient",
                    RedirectUri = baseUrl,
                    PostLogoutRedirectUri = baseUrl,
                    ResponseType = "id_token",
                    SignInAsAuthenticationType = "Cookies",
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        SecurityTokenValidated = async n =>
                        {
            //                            if (_idServerRedirectAfterLogout)
            //                            {
            //                                // Store extra claim in the token received so we can prove
            //                                // our identity at sign out and allow the post sign out redirect
            //                                var identity = n.AuthenticationTicket.Identity;
            //                                identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
            //                            }
                        },
                        RedirectToIdentityProvider = async n =>
                        {
            //                            if (_idServerRedirectAfterLogout)
            //                            {
            //                                if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
            //                                {
            //                                    // Send back the id_token we captured on validation to prove we are who we said,
            //                                    // so that the post logout re-direct can work....
            //                                    var idTokenClaim = n.OwinContext.Authentication.User.FindFirst("id_token");
            //                                    if (idTokenClaim != null)
            //                                        n.ProtocolMessage.IdTokenHint = idTokenClaim.Value;
            //                                }
            //                            }
                        }
                    }
                });

            app.UseNancy();

            //Needed to work on Mono but will work X-Plat
            app.UseAesDataProtectorProvider();

            app.UseStageMarker(PipelineStage.MapHandler);
        }
Example #26
0
        public void Configuration(IAppBuilder app)
        {
            LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider());
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Trace()
                         .CreateLogger();

            app.UseAesDataProtectorProvider();
            app.Map("/admin", adminApp =>
            {
                var factory = new IdentityManagerServiceFactory();

                factory.ConfigureSimpleIdentityManagerService("AspId");
                //factory.ConfigureCustomIdentityManagerServiceWithIntKeys("AspId_CustomPK");

                var adminOptions = new IdentityManagerOptions()
                {
                    Factory = factory
                };
                adminOptions.SecurityConfiguration.RequireSsl = false;
                adminApp.UseIdentityManager(adminOptions);
            });

            var idSvrFactory = Factory.Configure();

            idSvrFactory.ConfigureUserService("AspId");

            var viewOptions = new ViewServiceOptions
            {
                TemplatePath = this.basePath.TrimEnd(new char[] { '/' })
            };

            idSvrFactory.ViewService = new IdentityServer3.Core.Configuration.Registration <IViewService>(new ViewService(viewOptions));

            var options = new IdentityServerOptions
            {
                SiteName              = "IdentityServer3 - ViewSerive-AspNetIdentity",
                SigningCertificate    = Certificate.Get(),
                Factory               = idSvrFactory,
                RequireSsl            = false,
                AuthenticationOptions = new AuthenticationOptions
                {
                    IdentityProviders = ConfigureAdditionalIdentityProviders,
                }
            };

            app.Map("/core", core =>
            {
                core.UseIdentityServer(options);
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath = new PathString("/Content"),
                FileSystem  = new PhysicalFileSystem(Path.Combine(this.basePath, "Content"))
            });

            var config = new HttpConfiguration();

            //  config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("API", "api/{controller}/{action}", new { controller = "Home", action = "Get" });
            app.UseWebApi(config);
        }