Esempio n. 1
0
        public void Configuration(IAppBuilder app)
        {
            LoadIdenityServerConfiguration();
            LoadCredentialBasicAuthConfiguration();

            app.UseBasicAuthentication(
                new BasicAuthenticationOptions(
                    "SecureAPI",
                    async(username, password) => await Authenticate(username, password)));

            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = urlIdentityServer,
                RequiredScopes = new[] { scopesIdentityServer },
            });

            app.UseWebApi(WebApiConfig.Register());

            var stringConnection = Notification.Repository.Connections.Connection.Get("Notification");
            var database         = new MongoUrlBuilder(stringConnection).DatabaseName;

            GlobalConfiguration.Configuration.UseMongoStorage(stringConnection, database);

            var repository = new NotificationRepository();

            repository.CreateIndexNotificationRepository();

            app.UseHangfireDashboard();
            app.UseHangfireServer();
        }
Esempio n. 2
0
        public void ConfigureAuth(IAppBuilder app)
        {
            basicUsers = new Dictionary <string, string>();
            string appSet = System.Configuration.ConfigurationManager.AppSettings["BasicAuthUsers"];

            if (!string.IsNullOrWhiteSpace(appSet))
            {
                foreach (string ident in appSet.Split(';'))
                {
                    if (!string.IsNullOrWhiteSpace(ident))
                    {
                        string[] login = ident.Split(',');
                        basicUsers.Add(login[0].Trim().ToLower(), login[1].Trim());
                    }
                }
            }
            Func <string, string, Task <IEnumerable <Claim> > > validateUser = (string uname, string password) => {
                IEnumerable <Claim> toReturn = null;
                if (basicUsers.ContainsKey(uname.ToLower()))
                {
                    if (basicUsers[uname.ToLower()] == password)
                    {
                        toReturn = new List <Claim>()
                        {
                            new Claim("authed", "true")
                        };
                    }
                }
                return(Task.FromResult(toReturn));
            };

            Thinktecture.IdentityModel.Owin.BasicAuthenticationOptions opts = new Thinktecture.IdentityModel.Owin.BasicAuthenticationOptions("BloodGulch",
                                                                                                                                             new Thinktecture.IdentityModel.Owin.BasicAuthenticationMiddleware.CredentialValidationFunction(validateUser));
            app.UseBasicAuthentication(opts);
        }
Esempio n. 3
0
        public void Configuration(IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();

            if (Settings.Instance.Log.Level == "trace")
            {
                config.MessageHandlers.Add(new MessageLoggingHandler());
            }

            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            var xmlFormatter = new AtomXmlMediaTypeFormatter();

            config.Formatters.Insert(0, xmlFormatter);

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                "Web",
                "{*filename}",
                new { controller = "Web", action = "ServeIndex" }
                );

            if (Settings.Instance.Authentication.Enabled)
            {
                appBuilder.UseBasicAuthentication();
            }
            appBuilder.UseWebApi(config);
        }
Esempio n. 4
0
 public void ConfigureAuth( IAppBuilder app )
 {
     basicUsers = new Dictionary<string, string>();
     string appSet = System.Configuration.ConfigurationManager.AppSettings["BasicAuthUsers"];
     if ( !string.IsNullOrWhiteSpace( appSet ) ) {
         foreach ( string ident in appSet.Split( ';' ) ) {
             if ( !string.IsNullOrWhiteSpace( ident ) ) {
                 string[] login = ident.Split( ',' );
                 basicUsers.Add( login[0].Trim().ToLower(), login[1].Trim() );
             }
         }
     }
     Func<string, string, Task<IEnumerable<Claim>>> validateUser = ( string uname, string password ) => {
         IEnumerable<Claim> toReturn = null;
         if ( basicUsers.ContainsKey( uname.ToLower() ) ) {
             if ( basicUsers[uname.ToLower()] == password ) {
                 toReturn = new List<Claim>() { new Claim( "authed", "true" ) };
             }
         }
         return Task.FromResult( toReturn );
     };
     Thinktecture.IdentityModel.Owin.BasicAuthenticationOptions opts = new Thinktecture.IdentityModel.Owin.BasicAuthenticationOptions( "BloodGulch",
         new Thinktecture.IdentityModel.Owin.BasicAuthenticationMiddleware.CredentialValidationFunction( validateUser ) );
     app.UseBasicAuthentication( opts );
 }
Esempio n. 5
0
        public void Configuration(IAppBuilder appBuilder)
        {
            var sfConfig = appBuilder.GetUnityContainer().Resolve <ServiceContext>().CodePackageActivationContext.GetConfigurationPackageObject("Config");
            var target   = sfConfig.Settings.Sections["AppSettings"].Parameters["BasicAuth"].Value;

            appBuilder.UseBasicAuthentication(new BasicAuthenticationOptions("messagecluster", (username, password) => {
                if (string.Equals(target, $"{username}:{password}"))
                {
                    return(Task.FromResult <IEnumerable <Claim> >(new[] { new Claim("sub", "username") }));
                }
                return(null);
            }));

            HttpConfiguration config = new HttpConfiguration();

            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter("Basic"));
            config.MapHttpAttributeRoutes();
            config.Filters.Add(new ValidateModelAttribute());

            var jsonFormatter = new JsonMediaTypeFormatter();

            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
            config.MessageHandlers.Insert(0, new KatanaDependencyResolver());

            appBuilder.UseWebApi(config);
        }
        public void Configuration(IAppBuilder app)
        {
            // Setup authentication.
            app.UseBasicAuthentication("stopwatch", Authenticate.Basic);
            app.UseAPIKeyAuthentication(Authenticate.APIKey);

            // Build DI container. This is shared between Web API and SignalR.
            long initialTicks     = DateTime.UtcNow.Ticks;
            var  stopwatchService = new StopwatchService(
                new InMemoryTimestampRepository(), // Uncomment to use in-memory data storage.
                //new AzureTableStorageTimestampRepository(), // Uncomment to use Azure Table Storage.
                () =>                              // Timer will advance 1ms each time it is queried.
            {
                initialTicks += TimeSpan.TicksPerMillisecond;
                return(initialTicks);
            });
            var container = new Container();

            container.RegisterSingleton(typeof(IStopwatchService), stopwatchService);
            // That's the SignalR timer to broadcast elapsed time to user when subject requests.
            container.RegisterSingleton(typeof(IObservable <Unit>), StopwatchHubTest.Subject.AsObservable());

            // Setup Web API.
            var httpConfiguration = new HttpConfiguration();

            ConfigureWebApi(httpConfiguration, container);
            app.UseWebApi(httpConfiguration);

            // Setup SignalR.
            var hubConfiguration = new HubConfiguration();

            ConfigureSignalR(hubConfiguration, container);
            app.MapSignalR(hubConfiguration);
        }
Esempio n. 7
0
        public void Configuration(IAppBuilder app)
        {
            // Setup authentication.
            app.UseBasicAuthentication("stopwatch", Authenticate.Basic);
            app.UseAPIKeyAuthentication(Authenticate.APIKey);

            // Build DI container. This is shared between Web API and SignalR.
            var stopwatchService = new StopwatchService(
                new InMemoryTimestampRepository(), // Uncomment to use in-memory data storage.
                //new AzureTableStorageTimestampRepository(), // Uncomment to use Azure Table Storage.
                () => DateTime.UtcNow.Ticks);
            var container = new Container();

            container.RegisterSingleton(typeof(IStopwatchService), stopwatchService);
            // That's the SignalR timer to broadcast elapsed time to user each second.
            container.RegisterSingleton(
                typeof(IObservable <Unit>),
                Observable.Interval(TimeSpan.FromSeconds(1)).Select(_ => Unit.Default));

            // Setup Web API.
            var httpConfiguration = new HttpConfiguration();

            ConfigureWebApi(httpConfiguration, container);
            app.UseWebApi(httpConfiguration);

            // Setup SignalR.
            var hubConfiguration = new HubConfiguration();

            ConfigureSignalR(hubConfiguration, container);
            app.MapSignalR(hubConfiguration);
        }
Esempio n. 8
0
        public void Configuration(IAppBuilder appBuilder)
        {
            var configuration = new HttpConfiguration();

            configuration.Routes.MapHttpRoute("default", "api/{controller}");

            appBuilder.UseBasicAuthentication("MyApp", ValidateUser);
            appBuilder.UseWebApi(configuration);
        }
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();

            app.UseBasicAuthentication(new BasicAuthenticationOptions("SecureApi",
                async (username, password) => await Authenticate(username, password)));

            app.UseWebApi(config);
        }
Esempio n. 10
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            app.UseBasicAuthentication(new BasicAuthenticationOptions("SecureApi",
                                                                      async(username, password) => await Authenticate(username, password)));

            app.UseWebApi(config);
        }
Esempio n. 11
0
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);

            app.Use <DeviceGuidAuthenticationMiddleware>(new DeviceGuidTokenAuthenticationOptions());
            app.Use <AdminGuidAuthenticationMiddleware>(new AdminGuidTokenAuthenticationOptions());
            app.Use <SkautIsAuthenticationMiddleware>(new SkautIsAuthenticationOptions());
            app.UseBasicAuthentication(new AdminBasicAuthenticationOptions());
            app.UseWebApi(config);
        }
Esempio n. 12
0
        public void Configuration(IAppBuilder app)
        {
            var configuration = new HttpConfiguration();
            configuration.Routes.MapHttpRoute(
                "default",
                "api/{controller}"
                );

            app.Use(typeof(TestMiddleware));

            app.UseBasicAuthentication("Demo", ValidateUser);

            app.UseWebApi(configuration);
        }
Esempio n. 13
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            app.UseAutofacMiddleware(_container);
            var auth = new Authentication(_users);

            app.UseBasicAuthentication("gitdb", auth.ValidateUsernameAndPassword);
            config.MapHttpAttributeRoutes();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(_container);

            app.UseStageMarker(PipelineStage.MapHandler);
            app.UseWebApi(config);
        }
Esempio n. 14
0
        public void Configuration(IAppBuilder app)
        {
            var configuration = new HttpConfiguration();

            configuration.Routes.MapHttpRoute(
                "default",
                "api/{controller}");

            app.UseBasicAuthentication("Demo", ValidateUsers);

            app.UseClientCertificateAuthentication(X509RevocationMode.NoCheck);

            app.UseWebApi(configuration);
        }
Esempio n. 15
0
        // Configures the Web API. This class is a parameter in the WerbApp.Start method in the main class.
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
            appBuilder.UseBasicAuthentication(new BasicAuthenticationOptions("SecureApi",
                                                                             async(username, password) => await Authenticate(username, password)));

            appBuilder.UseWebApi(config);
        }
Esempio n. 16
0
        public static void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            config.Routes.MapHttpRoute("Default", "{controller}/{customerID}", new { controller = "values", customerID = RouteParameter.Optional });
            config.MapHttpAttributeRoutes();

            app.UseBasicAuthentication(new BasicAuthenticationOptions
            {
                AuthenticateBasicCredentials = AuthenticateBasicCredentials,
                Realm = "foo"
            });

            app.UseWebApi(config);
        }
Esempio n. 17
0
        // 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(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/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);

            app.UseBasicAuthentication(new BasicAuthenticationOptions("SecureApi",
                                                                      async(username, password) => await Authenticate(username, password)));

            // 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)
        {
            // require SSL and client certificates
            app.RequireSsl(requireClientCertificate: true);

            // basic authentication
            app.UseBasicAuthentication("katanademo", ValidateUser);

            // client certificates
            app.UseClientCertificateAuthentication(X509RevocationMode.NoCheck);

            // transform claims to application identity
            app.UseClaimsTransformation(TransformClaims);

            app.UseWebApi(WebApiConfig.Register());
        }
        public void Configuration(IAppBuilder app)
        {
            // require SSL and client certificates
            app.RequireSsl(requireClientCertificate: true);

            // basic authentication
            app.UseBasicAuthentication("katanademo", ValidateUser);
            
            // client certificates
            app.UseClientCertificateAuthentication(X509RevocationMode.NoCheck);

            // transform claims to application identity
            app.UseClaimsTransformation(TransformClaims);

            app.UseWebApi(WebApiConfig.Register());
        }
Esempio n. 20
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseBasicAuthentication(new BasicAuthenticationOptions("demo", ValidateBasicUser));

            var oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider(),
                ApplicationCanDisplayErrors = true
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(oAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
Esempio n. 21
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            config.Services.Add(typeof(IExceptionLogger), new ExceptionLogger());
            app.UseAutofacMiddleware(_container);
            var auth = new Authentication(_users);

            app.UseBasicAuthentication("appy.gitdb", auth.ValidateUsernameAndPassword);
            config.MapHttpAttributeRoutes();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(_container);

            app.Use <LoggingMiddleware>();
            app.UseCompressionModule(OwinCompression.DefaultCompressionSettings);
            app.UseStageMarker(PipelineStage.MapHandler);
            app.UseWebApi(config);
        }
Esempio n. 22
0
        public void Configuration(IAppBuilder appBuilder)
        {
            HttpConfiguration config = new HttpConfiguration();

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

            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

            appBuilder.UseBasicAuthentication(new BasicAuthenticationOptions("SecureApi",
                                                                             async(username, password) => await Authenticate(username, password)));

            appBuilder.UseNinjectMiddleware(CreateKernel);
            appBuilder.UseNinjectWebApi(config);
        }
Esempio n. 23
0
        public void Configuration(IAppBuilder app)
        {
            // Use basic authentication middleware
            app.UseBasicAuthentication("KatanaBasicAuth", Validator);

            // Configure web api routing
            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{controller}/{id}",
                new { id = RouteParameter.Optional });
            app.UseWebApi(config);

            // Add error, welcome pages
            app.UseErrorPage();
            app.UseWelcomePage();
        }
Esempio n. 24
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(MyCtx.Create);
            app.CreatePerOwinContext(() => new MyUserManager(new MyUserStore(new MyCtx())));

            var basicAuthOptions = new BasicAuthenticationOptions("KMailWebManager", validationCallback);
            app.UseBasicAuthentication(basicAuthOptions);

            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);
        }
Esempio n. 25
0
        public void Configuration(IAppBuilder app)
        {
            LoadUrlIdenityServerConfiguration();
            LoadCredentialBasicAuthConfiguration();

            app.UseBasicAuthentication(new BasicAuthenticationOptions("SecureAPI",
                                                                      async(username, password) =>
                                                                      await Authenticate(username, password)));

            app.UseSignalTokenAuthentication();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                //endereço identity server
                Authority          = urlIdentityServer,
                AuthenticationType = "Bearer",
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                RequiredScopes     = new[] { scopesIdentityServer }
            });

            //app.MapSignalR();
            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);

                // add middleware to translate the query string token
                // passed by SignalR into an Authorization Bearer header
                var hubConfiguration = new HubConfiguration
                {
                    // You can enable JSONP by uncommenting line below.
                    // JSONP requests are insecure but some older browsers (and some
                    // versions of IE) require JSONP to work cross domain
                    // EnableJSONP = true
                };
                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the "/signalr"
                // path.
                map.RunSignalR(hubConfiguration);
            });
        }
Esempio n. 26
0
        public void Configuration(IAppBuilder app)
        {
            // Use basic authentication middleware
            app.UseBasicAuthentication("KatanaBasicAuth", Validator);

            // Configure web api routing
            var config = new HttpConfiguration();

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

            // Add error, welcome pages
            app.UseErrorPage();
            app.UseWelcomePage();
        }
Esempio n. 27
0
        public void Configuration(IAppBuilder appBuilder)
        {
            HttpConfiguration config = new HttpConfiguration();

            //configure basic authentication
            //a valid username/password combination is one in which they match
            //hey, it's a demo, give me a break...
            appBuilder.UseBasicAuthentication("DemoRealm", (u, p) => u.Equals(p));


            // Web API routes
            config.MapHttpAttributeRoutes();

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

            appBuilder.UseWebApi(config);
        }
Esempio n. 28
0
        public void Configuration(IAppBuilder app)
        {
            var httpConfiguration = new HttpConfiguration();

            //app.UseIpFiltering(remoteAddress =>
            //{
            //    var bytes = remoteAddress.GetAddressBytes();
            //    bool addressToReject = bytes[0] != 192 && bytes[0] != 172 && bytes[0] != 10 && bytes[0] != 127 && bytes[0] != 0;
            //    return addressToReject;
            //});

            app.UseHeaderFiltering(headers =>
            {
                if (ConfigurationProvider.TokenHeaderFilteringEnabled)
                {
                    return(this.ValidateTokenHeader(headers));
                }

                return(true);
            });

            app.UseBasicAuthentication(this.LogOn);

            // Configure Web API Routes:
            // - Enable Attribute Mapping
            // - Enable Default routes at /api.
            httpConfiguration.MapHttpAttributeRoutes();
            httpConfiguration.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            app.UseWebApi(httpConfiguration);
            this.SetupDatabase();
        }
Esempio n. 29
0
        public static void UseBasicAuthentication(this IAppBuilder owinApp, BasicAuthUserPassValidator userPassValidator)
        {
            owinApp.UseBasicAuthentication(new BasicAuthenticationOptions("BasicAuth", async(username, password) =>
            {
                string userId = await userPassValidator(username, password);

                if (!string.IsNullOrEmpty(userId))
                {
                    return(new List <System.Security.Claims.Claim>
                    {
                        new System.Security.Claims.Claim("client_id", "basic-auth"),
                        new System.Security.Claims.Claim("sub", userId),
                        new System.Security.Claims.Claim("primary_sid", userId),
                        new System.Security.Claims.Claim("upn", userId),
                        new System.Security.Claims.Claim("name", userId),
                        new System.Security.Claims.Claim("given_name", userId)
                    });
                }
                else
                {
                    return(null);
                }
            }));
        }
Esempio n. 30
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public static void Configuration(IAppBuilder appBuilder)
        {
            var container = BootstrapContainer();

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

            config.MapHttpAttributeRoutes();

            // NTLM
            ////var listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
            ////listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;

            // api key auth
            appBuilder.UseAPIKeyAuthentication(new APIKeyAuthenticationOptions("ExpectedKey"));

            // set custom identity
            var identityDataProvider = container.Resolve <IIdentityDataProvider>();

            appBuilder.UseBasicAuthentication(async(id, secret) => await identityDataProvider.GetIdentity(id, secret).ConfigureAwait(false));

            appBuilder.UseWindsorDependencyResolverScope(config, container);
            appBuilder.UseWebApi(config);
        }
Esempio n. 31
0
        // 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(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/Account/ExternalLogin"),
            //    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            //    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 = ""
            //});

            // This must come first to intercept the /Token requests
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            var oauthServerConfig = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = AuthenticationConstants.AllowInsecureHttp,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = SecurityTokenConstants.TokenLifeTime,
                Provider             = new MembershipRebootOAuthAuthorizationServerProvider(),
                RefreshTokenProvider = new MembershipRebootOAuthAuthorizationServerRefreshTokenProvider()
            };

            app.UseOAuthAuthorizationServer(oauthServerConfig);

            var oauthConfig = new OAuthBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AuthenticationType = AuthenticationConstants.BearerAuthType
            };

            app.UseOAuthBearerAuthentication(oauthConfig);

            app.UseBasicAuthentication(new BasicAuthenticationOptions("qssolutions.net", UserAccountServiceFactory.Create())
            {
                AuthenticationType = AuthenticationConstants.BasicAuthType,
                AuthenticationMode = AuthenticationMode.Active
            });
        }
Esempio n. 32
0
        // This method is auto-detected by the OWIN pipeline. DO NOT RENAME IT!
        public static void Configuration(IAppBuilder app)
        {
            // Get config
            var config = Container.Kernel.Get<ConfigurationService>();
            var auth = Container.Kernel.Get<AuthenticationService>();

            // Configure logging
            app.SetLoggerFactory(new DiagnosticsLoggerFactory());

            if (config.Current.RequireSSL)
            {
                // Put a middleware at the top of the stack to force the user over to SSL
                // if authenticated.
                //app.UseForceSslWhenAuthenticated(config.Current.SSLPort);

                // Put a middleware at the top of the stack to force the user over to SSL always
                app.UseForceSslAlways(config.Current.SSLPort);
            }

            app.UseBasicAuthentication(new BasicAuthenticationOptions()
            {
                AuthenticationMode = AuthenticationMode.Active,
                AuthenticationType = AuthenticationTypes.LocalUser,
            });
            app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.LocalUser);

            if (config.Current.ForceAuth)
            {
                app.Authorize();
            }

            //// Get the local user auth provider, if present and attach it first
            //Authenticator localUserAuther;
            //if (auth.Authenticators.TryGetValue(Authenticator.GetName(typeof(LocalUserAuthenticator)), out localUserAuther))
            //{
            //    // Configure cookie auth now
            //    localUserAuther.Startup(config, app);
            //}

            //// Attach external sign-in cookie middleware
            //app.SetDefaultSignInAsAuthenticationType(AuthenticationTypes.External);
            //app.UseCookieAuthentication(new CookieAuthenticationOptions()
            //{
            //    AuthenticationType = AuthenticationTypes.External,
            //    AuthenticationMode = AuthenticationMode.Passive,
            //    CookieName = ".AspNet." + AuthenticationTypes.External,
            //    ExpireTimeSpan = TimeSpan.FromMinutes(5)
            //});

            //// Attach non-cookie auth providers
            //var nonCookieAuthers = auth
            //    .Authenticators
            //    .Where(p => !String.Equals(
            //        p.Key,
            //        Authenticator.GetName(typeof(LocalUserAuthenticator)),
            //        StringComparison.OrdinalIgnoreCase))
            //    .Select(p => p.Value);
            //foreach (var auther in nonCookieAuthers)
            //{
            //    auther.Startup(config, 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.UseBasicAuthentication(new Thinktecture.IdentityModel.Owin.BasicAuthenticationOptions(string.Empty,
         new Thinktecture.IdentityModel.Owin.BasicAuthenticationMiddleware.CredentialValidationFunction(BasicAuthenticate)));
 }
Esempio n. 34
0
 public void Configuration(IAppBuilder app)
 {
     app.UseBasicAuthentication("Demo", ValidateBasicAuth);
     app.UseWebApi(WebApiConfig.Register());
 }
Esempio n. 35
0
 public void Configuration(IAppBuilder app)
 {
     app.UseBasicAuthentication("Demo", this.ValidateUsers);
 }
        public static IAppBuilder UseBasicAuthentication(this IAppBuilder app, string realm, BasicAuthenticationMiddleware.CredentialValidationFunction validationFunction)
        {
            var options = new BasicAuthenticationOptions(realm, validationFunction);

            return(app.UseBasicAuthentication(options));
        }
Esempio n. 37
0
        public void ConfigureAuth(IAppBuilder app)
        {
            var basicAuthOptions = new BasicAuthenticationOptions("contosoodata", async(username, password) => await Authenticate(username, password));

            app.UseBasicAuthentication(basicAuthOptions);
        }
Esempio n. 38
0
 public void Configuration(IAppBuilder app)
 {
     app.UseBasicAuthentication("Demo", this.ValidateUsers);
 }
Esempio n. 39
0
        public void ConfigureOAuth(IAppBuilder app)
        {
           app.UseBasicAuthentication(new BasicAuthenticationOptions("demo", ValidateBasicUser));

            var oAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider(),
                ApplicationCanDisplayErrors = true
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(oAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
 
        }
Esempio n. 40
0
 // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
 public void ConfigureAuth(IAppBuilder app)
 {
     app.UseBasicAuthentication(new Thinktecture.IdentityModel.Owin.BasicAuthenticationOptions(string.Empty,
                                                                                               new Thinktecture.IdentityModel.Owin.BasicAuthenticationMiddleware.CredentialValidationFunction(BasicAuthenticate)));
 }