Esempio n. 1
1
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                // The HttpSignatureValidation middleware looks for another middleware called PoP
                AuthenticationType = "PoP",

                Authority = "https://localhost:44333/core",
                RequiredScopes = new[] { "write" },

                // client credentials for the introspection endpoint
                ClientId = "write",
                ClientSecret = "secret",

                // this is used to extract the access token from the pop token
                TokenProvider = new OAuthBearerAuthenticationProvider
                {
                    OnRequestToken = async ctx =>
                    {
                        ctx.Token = await DefaultPopTokenProvider.GetAccessTokenFromPopTokenAsync(ctx.OwinContext.Environment);
                    }
                }
            });

            // this registers the middleware that does the signature validation of the request against the pop token secret
            app.UseHttpSignatureValidation();

            app.UseWebApi(WebApiConfig.Register());
        }
        public void Configuration(IAppBuilder app)
        {
            // # 1) Bearer token authentication
            // Nuget source code and documentation https://github.com/IdentityServer/IdentityServer3.AccessTokenValidation
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                // accept only tokens issued by IdentityServer
                Authority = IdentityServerUrl,
                // accept only tokens that are issued for our API
                RequiredScopes = new[] { "tickets_api" }, // There is an scope defined in Identity Server that some clients can use 

                ValidationMode = ValidationMode.Local // JWT Local validation
            });

            // # 2) Web api 
            var config = new HttpConfiguration();

            // routing
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}");

            // JSON formatter
            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());

            app.UseWebApi(config);
        }
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
            JwtSecurityTokenHandler.OutboundClaimTypeMap = new Dictionary<string, string>();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "http://localhost:49907/core",
                ValidationMode = ValidationMode.Local, // JWT
                TokenProvider = new OAuthBearerAuthenticationProvider()
                {
                    OnValidateIdentity = ctx =>
                    {
                        var claims = new List<Claim>(ctx.Ticket.Identity.Claims);
                        claims.Add(new Claim("name", "johnny"));
                        var identity = new ClaimsIdentity(claims, ctx.Ticket.Identity.AuthenticationType, "name", "role");
                        return Task.FromResult(ctx.Validated(identity));
                    }
                }
            });

            var config = new HttpConfiguration();
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            config.MapHttpAttributeRoutes();
            app.UseWebApi(config);
        }
Esempio n. 4
0
 public void Configuration(IAppBuilder app)
 {
     app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
     {
         Authority = "https://authtestspike.au.auth0.com"
     });
 }
Esempio n. 5
0
        public void Configuration(IAppBuilder app)
        {
            // Allow all origins
            app.UseCors(CorsOptions.AllowAll);

            // Wire token validation
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44300",

                // For access to the introspection endpoint
                ClientId     = "api",
                ClientSecret = "api-secret",

                RequiredScopes = new[] { "api" }
            });

            // Wire Web API
            var httpConfiguration = new HttpConfiguration();

            httpConfiguration.MapHttpAttributeRoutes();
            httpConfiguration.Filters.Add(new AuthorizeAttribute());

            app.UseWebApi(httpConfiguration);
        }
        public void Configuration(IAppBuilder app)
        {
            // Create container
            var container = SetupContainer();

            // Setup token based authentication
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44302",
                ValidationMode = ValidationMode.ValidationEndpoint,

                RequiredScopes = new[] { "Api" }
            });

            // Configure CORS (Cross Origin Resource Sharing)
            app.UseCors(CorsOptions.AllowAll);

            // Create new http configuration
            var config = new HttpConfiguration();

            // Configure webapi
            WebApiConfig.Configure(config, container.GetInstance<IDependencyResolver>());

            // Register web api
            app.UseWebApi(config);
        }
Esempio n. 7
0
        public void Configuration(IAppBuilder app)
        {
            //AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            // accept access tokens from identityserver and require a scope of 'api1'
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = "http://localhost:5000",
                ValidationMode = ValidationMode.Local,
                RequiredScopes = new List <string> {
                    "Api2"
                }
            });

            // configure web api
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            // require authentication for all controllers
            config.Filters.Add(new AuthorizeAttribute());

            app.UseWebApi(config);
        }
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            // Unterstützung für identity server access tokens
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
                {
                    // basis URL
                    Authority = "https://localhost:44345",
                    ValidationMode = ValidationMode.Local,

                    // konfigurierte scope in identity server
                    RequiredScopes = new[] { "webapi" }
                });

            // web api konfiguration mit attribute routing
            var webApiConfig = new HttpConfiguration();
            webApiConfig.MapHttpAttributeRoutes();

            // CORS aktivieren
            var corsAttribute = new EnableCorsAttribute("https://localhost:44300", "*", "*");
            webApiConfig.EnableCors(corsAttribute);

            // kein anonymer zugriff erlaubt
            webApiConfig.Filters.Add(new AuthorizeAttribute());

            // web api einbinden
            app.UseWebApi(webApiConfig);
        }
Esempio n. 9
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseIdentityServerBearerTokenAuthentication(
                new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = "http://localhost:5000",
                ValidationMode = ValidationMode.Local,
                RequiredScopes = new[] { "api2" },
                ClientSecret   = "secret3",
                ClientId       = "api2"
            });

            //configure web api
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}",
                defaults: new { id = RouteParameter.Optional }
                );
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            app.UseCors(CorsOptions.AllowAll);

            app.UseNLog((eventType) => LogLevel.Debug);

            app.UseWebApi(config);
        }
Esempio n. 10
0
        public void Configuration(IAppBuilder app)
        {
            // http://stackoverflow.com/questions/28473320/ninject-causes-notimplementedexception-at-httpcontextbase-get-response
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.Filters.Add(new LogActionAttribute());

            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterModule <AdvisorModule>();

            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "http://localhost:4959"
            });

            app.UseWebApi(config);

            config.EnsureInitialized();
            GlobalConfiguration.Configuration.EnsureInitialized();
        }
Esempio n. 11
0
        public void Configuration(IAppBuilder app)
        {
            // Disables default mapping of incoming claims
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            // Configures authentication using "Bearer" tokens with IdentityServer.
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                // The issuer of the tokens
                Authority = "https://timesheetsts.azurewebsites.net",
                ValidationMode = ValidationMode.Local,
                RequiredScopes = new[] { TimesheetConstants.ApiScope }, // When accessing our API, a token must have the "timesheet-api" scope
                NameClaimType = "name", // Rename the default Name/Role claimtypes from their SOAP versions to IdentityServer.
                RoleClaimType = "role"
            });

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes(); // Use attribute routing

            config.SuppressDefaultHostAuthentication(); // If IIS has set a User on our request, remove it again
            config.Filters.Add(new AuthorizeAttribute()); // Users must be logged on for each request
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // And look for a Bearer token to authenticate a user

            config.Formatters.Remove(config.Formatters.XmlFormatter); // Remove the XML formatter, we're only supporting JSON
            config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver() // Set up camelCase names
            };

            // Validation for our POST models
            FluentValidationModelValidatorProvider.Configure(config);

            // Start the Web API middleware
            app.UseWebApi(config);
        }
        public override HttpConfiguration GetHttpConfiguration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();
            var config = new HttpConfiguration();

            //Autofac Filters primarily to make in memory testing easier
            builder.Register(c => new IdSrvAuthorizeAttributeFake())
                .As<IAutofacAuthorizationFilter>()
                .AsWebApiAuthorizationFilterFor<ClaimsController>()
                .InstancePerRequest();

            builder.Register(c => new IdSrvAuthorizeAttributeFake())
                .As<IAutofacAuthorizationFilter>()
                .AsWebApiAuthorizationFilterFor<LinkExternalProviderController>(c => c.Post(default(LinkExternalProviderController.RegisterExternalBindingModel)))
                .InstancePerRequest();

            builder.Register(c => new IdSrvAuthorizeAttributeFake())
                .As<IAutofacAuthorizationFilter>()
                .AsWebApiAuthorizationFilterFor<UnLinkExternalProviderController>()
                .InstancePerRequest();

            builder.RegisterType<MrUserAccountServiceFake>()
                .As<IMrUserAccountService>()
                .InstancePerRequest();

            builder.RegisterType<LinkedAccountClaim>().InstancePerLifetimeScope();

            builder.Register(c => new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "405547628913-afp6rob22l602dembl7eqnseb9vmrbqs.apps.googleusercontent.com",
                ClientSecret = "ENxb5ZPcOl_BHSWfUTUQecxw",
                Provider = new GoogleAuthProvider()
            });

            builder.Register(c => new FacebookAuthenticationOptions()
            {
                AppId = "1617509121824168",
                AppSecret = "dc36301f5ec7a3e30adf3cb6a1a8fddc",
                Provider = new FacebookAuthProvider()
            });

            builder.RegisterApiControllers(typeof(Startup).Assembly);

            builder.RegisterWebApiFilterProvider(config);

            var container = builder.Build();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44333/core",
                RequiredScopes = new[] { "api1" }
            });

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

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            return config;
        }
Esempio n. 13
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. 14
0
        public void Configuration(IAppBuilder app)
        {
            // accept access tokens from identityserver and require a scope of 'api1'
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = "http://localhost:50001",
                ValidationMode = ValidationMode.ValidationEndpoint,

                RequiredScopes = new[] { "api.seguridad" }
            });

            // configure web api
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

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

            // require authentication for all controllers
            config.Filters.Add(new AuthorizeAttribute());

            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

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

            app.UseWebApi(config);
        }
Esempio n. 15
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. 16
0
        public void Configuration(IAppBuilder app)
        {
            var config = GlobalConfiguration.Configuration;

            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterModule <SocialNetworkModule>();

            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            //var certificate = new X509Certificate2(Convert.FromBase64String("MIIC9TCCAd2gAwIBAgIQMlrWG4601pBI01XrMJ7txjANBgkqhkiG9w0BAQsFADAXMRUwEwYDVQQDEwxEaXZpbmVMb3ZlLTIwHhcNMTgwODE1MDM0NDI0WhcNMTkwODE0MDAwMDAwWjAXMRUwEwYDVQQDEwxEaXZpbmVMb3ZlLTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDeEZbbcn0plLQxS02KWAED401N+GWw2zhbQYWVXgOMQR0p83oIWrJV96bOa/IrM9xmRagPmHlqlMOAhjyYh9Nt4eult6pphCYFES9EFJnNsdlqlKDV0xqn1G4KeTW4xorrMYgJ8uyMIVxU+fy/9ulaLu0aydP4Zjao5Y2h6LfSzePXfUQoHt3dtsmj/j9g5DAc8aevGt4+tU03OZdV+fjBw+V7A81yxPq0SRZ80BRaVmGjEJNLXVVb5U9KhtbQOBi1YNUoSAi0aUgzHosAFiGfhA6GO8Ol870XOA9yJtDr/HnbiFqBdFS5YsdtGv/QKl+THe8Isyu2bp/MB7FxzKqdAgMBAAGjPTA7MAsGA1UdDwQEAwIEMDATBgNVHSUEDDAKBggrBgEFBQcDATAXBgNVHREEEDAOggxEaXZpbmVMb3ZlLTIwDQYJKoZIhvcNAQELBQADggEBAB4TEXbuiTdzUiFiT0GqNgf/WzCQF4DHfgziDUc8rk38jSWyNQcRXlAyiwtA0HwH0N0AYTBaALVvUt3ls0EX+zGG8TA1q4d7Y+zb4HmQ4su+EkLwFPCfgUlkDZ+YKsp5HfPQ0O9A0WC3XwfCj2bD9i7zipaPsCoD3hK78LpGMolqFdPgaPM71NXOatSxqgtaW73VklNRJF7JfUiBIEgL91LJIermlaGe3H4AgckKAu4Jx6jGjnyUEC4wcnB/N67l6zkNhPYKq2thVfdzpeGIX1S8e5ogUlKBt7IjmPidDwKAoNBHaNLsQtboBQLxHFl4+1t5II5QS8yl17UrsLNxLMM="));

            //app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            //{
            //    AllowedAudiences = new[] { "http://localhost:63409/resources" },
            //    TokenValidationParameters = new TokenValidationParameters
            //    {
            //        ValidAudience = "http://localhost:63409/resources",
            //        ValidIssuer = "http://localhost:63409",
            //        IssuerSigningKey = new X509SecurityKey(certificate)
            //    }
            //});

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "http://localhost:63409",
            });



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

            WebApiConfig.Register(config);
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = "http://localhost:52401",//Your url here
                RequiredScopes = new[] { "api" }
            });

            app.UseWebApi(config);
            var factory = InMemoryFactory.Create(Config.GetUsers().ToList(), Config.GetClients(), Config.GetScopes());

            app.UseIdentityServer(new IdentityServerOptions
            {
                IssuerUri      = "urn:identity",
                Factory        = factory,
                RequireSsl     = false, //DO NOT DO THIS IN PRODUCTION
                LoggingOptions = new LoggingOptions
                {
                    EnableWebApiDiagnostics    = true,
                    WebApiDiagnosticsIsVerbose = true
                },
                SigningCertificate = LoadCertificate()
            });
            app.UseNLog();
        }
Esempio n. 18
0
        public void Configuration(IAppBuilder app)
        {
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = "https://localhost:44395/identity",
                RequiredScopes = new[] { "sampleApi" }
            });

            // web api configuration
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            config.EnableSwagger("docs/{apiVersion}/swagger", c =>
            {
                c.SingleApiVersion("v1", "Super duper API");

                var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                var fileName      = Assembly
                                    .GetExecutingAssembly()
                                    .GetName()
                                    .Name + ".XML";
                var commentsFile = Path.Combine(baseDirectory, "bin", fileName);
                c.IncludeXmlComments(commentsFile);
            })
            //.EnableSwaggerUi()
            ;


            app.UseWebApi(config);
        }
Esempio n. 19
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
            });

            var baseUrl = ConfigurationManager.AppSettings["IdentityServerBaseUrl"];

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServer3.AccessTokenValidation.IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = baseUrl,
                ClientId       = "salesforce_client",
                RequiredScopes = new[] { "openid", "profile", "postman_api" }
            });

            //app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            //{
            //    ClientId = "expedo_client",
            //    AuthenticationType = "code",
            //    Authority = baseUrl,
            //    Scope = "postman_api",
            //    RedirectUri = "http://localhost:61744",
            //    RequireHttpsMetadata = false
            //});
        }
Esempio n. 20
0
        public void Configuration(IAppBuilder app)
        {
            var config = GlobalConfiguration.Configuration;

            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterModule <SocialNetworkModule>();

            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            //var certificate = new X509Certificate2(Convert.FromBase64String("MIIC1DCCAbygAwIBAgIQGU8bZgi257BN+dMzrNaQSDANBgkqhkiG9w0BAQUFADATMREwDwYDVQQDEwhGaWxpcC1QQzAeFw0xNjAyMjEwNjQ4MzdaFw0xNzAyMjEwMDAwMDBaMBMxETAPBgNVBAMTCEZpbGlwLVBDMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2/Ze/ru74n5YRTQKQujQOx4P7poPDuVfSi7aiBa7BV4pbBGXtzU8Mwt7LhewJnvbtJVdOj3S/4ndD3Zl65zV4RtqPAtGI0MJnMLxPibKaqnvikhLj/K5EEJ4yqXXlRSbH1VwwHzFtHmxnZd2KlmpNKF4WHaOzInoYmi36sffoAaikP7vmvUcO88X4tMP/KWxp5JZo5cQmLcKO3XiRDq532gezItq/p/iucHukF3WRMOL/73wB9bUcBU2/GIkFyB7Ne0YmJfhUopyCZnRh0UQP3DKrO1iKCy1Lje+TMi8hOoCfok8u1ZaJuueXgSf/J2S+AEe3M8D4OoYo6W0p+ZebwIDAQABoyQwIjALBgNVHQ8EBAMCBDAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDQYJKoZIhvcNAQEFBQADggEBANT5ltvrZJMHZNVO8juAO+PxyCSYmvIKNO2vBIglewmoF4vfdyABnAoIzHgKn5uvq1oPJCeiUHoNpzBMQiWqGW+NNL6wfTsZyfM24+EMv0ZDvkdm/B356tTZbPi/Pg/4vqDqAxbS6eE+VpBlZPHfDqCzlYKL+Ahhaq+xS4G0FJCvjWFt/EncwnVijuur3VYV+KxteAE+2ClI3N60nBH4UiOyigZ3Mwk0ONYu2R8X/AVMNpjKYXyXEGSi/JrCCNvINmnP4+SWpfFjVD8DDFK9VVsM6tl0HPM8qy3VkipCCnLZ6MRRIhrDnj8FnOZxCq7aI5fP7WDiwHKC/2zsX6LcOGs="));

            //app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            //{
            //    AllowedAudiences = new[] { "https://localhost:44335/resources" },
            //    TokenValidationParameters = new TokenValidationParameters
            //    {
            //        ValidAudience = "https://localhost:44335/resources",
            //        ValidIssuer = "https://localhost:44335",
            //        IssuerSigningKey = new X509SecurityKey(certificate)
            //    }
            //});

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44335"
            });

            app.UseWebApi(config);
        }
Esempio n. 21
0
        public void Configuration(IAppBuilder app)
        {
            // token validation
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = "https://localhost:44319/identity",
                RequiredScopes = new[] { "sampleApi" }
            });

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

            // web api configuration
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            app.UseWebApi(config);
        }
Esempio n. 22
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44333/core",
                RequiredScopes = new[] { "api" },
                NameClaimType = "name",
                RoleClaimType = "role",

                // client credentials for the introspection endpoint
                ClientId = "angularMaterial",
                ClientSecret = Guid.NewGuid().ToString()
            });

            var configuration = new HttpConfiguration();
            configuration.MapHttpAttributeRoutes();

            var jsonFormatter = configuration.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();

            if (jsonFormatter != null)
            {
                jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            }

            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseWebApi(configuration);

            app.UseNancy();
            app.UseStageMarker(PipelineStage.MapHandler);
        }
Esempio n. 23
0
        public void Configuration(IAppBuilder app)
        {
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json")
                                .Add(new WebConfigProvider())
                                .Build();
            var _certificateService = new WindowsCertificateService();
            var decryptionService   = new DecryptionService(_certificateService);

            var appConfig = new AppConfiguration();

            ConfigurationBinder.Bind(configuration, appConfig);

            var provider = new IdentityProviderSearchServiceConfigurationProvider(appConfig.EncryptionCertificateSettings, decryptionService);

            provider.GetAppConfiguration(appConfig);

            var logger = LogFactory.CreateTraceLogger(new LoggingLevelSwitch(), appConfig.ApplicationInsights);

            logger.Information("IdentityProviderSearchService is starting up...");

            appConfig.ConfigureIdentityServiceUrl();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = appConfig.IdentityServerConfidentialClientSettings.Authority,
                RequiredScopes = appConfig.IdentityServerConfidentialClientSettings.Scopes
            });

            app.UseNancy(opt => opt.Bootstrapper = new Bootstrapper(appConfig, logger));
            app.UseStageMarker(PipelineStage.MapHandler);
        }
Esempio n. 24
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = Constants.BaseAddress,            //只接受identityserver的令牌
                RequiredScopes = new[] { Constants.WebApi_Scope }, //只接受给generalapi的令牌

                ClientId     = Constants.WebApi_CLIENTID,
                ClientSecret = Constants.WebApi_SECRET
            });

            //autofac.webapi2.owin集成
            var builder = new ContainerBuilder();
            var config  = new HttpConfiguration();

            builder.RegisterApiControllers(typeof(WebApiApplication).Assembly).PropertiesAutowired();//注册api容器的实现
            Assembly[] assemblies = new Assembly[] { Assembly.Load("Lucy.Services") };
            builder.RegisterAssemblyTypes(assemblies)
            .Where(type => type.Name.EndsWith("Svc") && !type.IsAbstract)
            .AsImplementedInterfaces().PropertiesAutowired();//注册实现类
            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            app.UseWebApi(WebApiConfig.Register(config));
        }
Esempio n. 25
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            log.Info("Application Starting...");

            var config = new HttpConfiguration();

            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = "https://localhost:44333/core",
                RequiredScopes = new[] { "write" },

                // client credentials for the introspection endpoint
                //ClientId = "write",
                //ClientSecret = "secret"
            });

            RegisterAutofac(app, config);

            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap <PropertyModel, Property>();
                cfg.CreateMap <SearchParametersModel, SearchParameters>();
            });



            SwaggerConfig.Register(config);
            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }
        public void Configuration(IAppBuilder app)
        {
            app.Map("/identity", inner =>
            {
                var option = new IdentityServerOptions
                {
                    RequireSsl = false,
                    SiteName = "Same Server Identity Service",
                    EnableWelcomePage = false,
                    Factory = new IdentityServerServiceFactory()
                            .UseInMemoryClients(Clients.Get())
                            .UseInMemoryScopes(Scopes.Get())
                            .UseInMemoryUsers(Users.Get())
                };

                inner.UseIdentityServer(option);
            });

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions()
            {
                Authority = "http://*****:*****@"C:\myPath.txt") // remember to assign proper writing privileges on the file
                .CreateLogger();

        }
Esempio n. 27
0
 private static void SetupAccessTokenValidation(IAppBuilder app)
 {
     app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
     {
         Authority = "http://localhost:5000",
     });
 }
Esempio n. 28
0
        public void Configuration(IAppBuilder app)
        {
            /*var l = new LoggerConfiguration()
             *  .WriteTo.Trace(outputTemplate: "{Timestamp} [{Level}] ({Name}){NewLine} {Message}{NewLine}{Exception}")
             *  .WriteTo.File("c:\\temp\\webapi.log")
             *  .CreateLogger();
             *
             * l.Information("Hello");*/
            app.SetLoggerFactory(new MyLoggerFactory());

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = "https://identity.loc/core",
                RequiredScopes = new[] { "read" },
                EnableValidationResultCache = false,

                TokenProvider = new MyTokenProvider(),
                //ValidationMode = ValidationMode.ValidationEndpoint
            });

            var resolver = UnityConfig.BuildResolver();

            app.UseWebApi(WebApiConfig.Register(resolver));
        }
Esempio n. 29
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                // The HttpSignatureValidation middleware looks for another middleware called PoP
                AuthenticationType = "PoP",

                Authority      = "https://localhost:44333/core",
                RequiredScopes = new[] { "write" },

                // client credentials for the introspection endpoint
                ClientId     = "write",
                ClientSecret = "secret",

                // this is used to extract the access token from the pop token
                TokenProvider = new OAuthBearerAuthenticationProvider
                {
                    OnRequestToken = async ctx =>
                    {
                        ctx.Token = await DefaultPopTokenProvider.GetAccessTokenFromPopTokenAsync(ctx.OwinContext.Environment);
                    }
                }
            });

            // this registers the middleware that does the signature validation of the request against the pop token secret
            app.UseHttpSignatureValidation();

            app.UseWebApi(WebApiConfig.Register());
        }
Esempio n. 30
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "http://localhost:52401",//Your url here
                RequiredScopes = new[] {"api"}
            });

            app.UseWebApi(config);
            var factory = InMemoryFactory.Create(Config.GetUsers().ToList(), Config.GetClients(), Config.GetScopes());
            app.UseIdentityServer(new IdentityServerOptions
            {
                IssuerUri = "urn:identity",
                Factory = factory,
                RequireSsl = false, //DO NOT DO THIS IN PRODUCTION
                LoggingOptions = new LoggingOptions
                {
                 EnableWebApiDiagnostics   = true,
                 WebApiDiagnosticsIsVerbose = true
                },
                SigningCertificate = LoadCertificate()

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

            // accept access tokens from identityserver and require a scope of 'api1'
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44333",

                ClientId     = "api",
                ClientSecret = "api-secret",

                RequiredScopes = new[] { "api" }
            });

            // configure web api
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            // require authentication for all controllers
            config.Filters.Add(new AuthorizeAttribute());

            app.UseWebApi(config);
        }
Esempio n. 32
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            // Unterstützung für identity server access tokens
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                // basis URL
                Authority      = "https://localhost:44345",
                ValidationMode = ValidationMode.Local,

                // konfigurierte scope in identity server
                RequiredScopes = new[] { "webapi" }
            });

            // web api konfiguration mit attribute routing
            var webApiConfig = new HttpConfiguration();

            webApiConfig.MapHttpAttributeRoutes();

            // CORS aktivieren
            var corsAttribute = new EnableCorsAttribute("https://localhost:44300", "*", "*");

            webApiConfig.EnableCors(corsAttribute);

            // kein anonymer zugriff erlaubt
            webApiConfig.Filters.Add(new AuthorizeAttribute());

            // web api einbinden
            app.UseWebApi(webApiConfig);
        }
Esempio n. 33
0
        public void Configuration(IAppBuilder app)
        {
            log4net.Config.XmlConfigurator.Configure();

            this.Log().Info($"Starting {GetType().Namespace}");

            var configurationManager = new ConfigurationManager();
            var config = new HttpConfiguration();

            app.UseCors(CorsOptions.AllowAll);

            app.UseIoC(config);

            app.ConfigureWebApi(config);

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority         = configurationManager.GetByKey("CloudPlus.IdentityServerEndpoint"),
                ClientId          = configurationManager.GetByKey("CloudPlus.PortalClientId"),
                ClientSecret      = configurationManager.GetByKey("CloudPlus.PortalClientSecret"),
                RequiredScopes    = new[] { "write", "read" },
                NameClaimType     = ClaimTypes.NameIdentifier,
                DelayLoadMetadata = true
            });

            app.UseOpenApiSpecification(config);

            app.UseMessageBroker();

            app.UseWebApi(config);

            this.Log().Info($"Started {GetType().Namespace}");
        }
Esempio n. 34
0
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.InboundClaimFilter = new HashSet <string>();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions()
            {
                AuthenticationMode = AuthenticationMode.Active,
                IssuerName         = "http://localhost:44382",
                SigningCertificate = new X509Certificate2(Resources.bulbacourses, "123"),
                ValidationMode     = ValidationMode.Local,
            })
            .UseCors(new CorsOptions()
            {
                PolicyProvider = new CorsPolicyProvider()
                {
                    PolicyResolver = request => Task.FromResult(new CorsPolicy()
                    {
                        AllowAnyMethod = true,
                        AllowAnyOrigin = true,
                        AllowAnyHeader = true
                    })
                }
            });
        }
Esempio n. 35
0
        public void Configuration(IAppBuilder app)
        {
            // accept access tokens from identityserver and require a scope
            var tokenAuthenticationOptions = new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = Config.IdentityServerIdentityIP,
                ValidationMode = ValidationMode.ValidationEndpoint,

                RequiredScopes = new[] { "med_data_api" }
            };

            // plug OWIN middleware component for token authentication into the pipeline
            app.UseIdentityServerBearerTokenAuthentication(tokenAuthenticationOptions);

            // configuration of HttpServer instance
            var config = new HttpConfiguration();

            // map the attribute-defined routes for the application
            config.MapHttpAttributeRoutes();
            // require authentication for all controllers
            config.Filters.Add(new AuthorizeAttribute());

            // plug OWIN middleware component for WebApi into the pipeline
            app.UseWebApi(config);
        }
Esempio n. 36
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);
            app.Use <AuthorizationQsTokenExtractorMiddleware>();

            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();
            app.UseIdentityServerBearerTokenAuthentication(
                new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority           = ConfigurationManager.AppSettings["IdentityServerURL"],
                RequiredScopes      = new[] { "signalR" },
                PreserveAccessToken = true,
            });

            GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => new UserIdProvider());
            var hubConfiguration = new HubConfiguration {
                EnableDetailedErrors = true
            };

            app.MapSignalR(hubConfiguration);

            GlobalHost.HubPipeline.RequireAuthentication();  //// Require auth for everything in the pipeline

            /* Clean up unused references, also make sure signalr hub and assure is seperated as much as posisble */
        }
Esempio n. 37
0
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888

            var config = GlobalConfiguration.Configuration;

            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions()
            {
                Authority = "http://localhost:45204"
            });

            //var certificate = new X509Certificate2(Convert.FromBase64String("MIIEGzCCAwOgAwIBAgIJALZsYQ80GJftMA0GCSqGSIb3DQEBCwUAMIGjMQswCQYDVQQGEwJDQTEZMBcGA1UECAwQQnJpdGlzaCBDb2x1bWJpYTESMBAGA1UEBwwJVmFuY291dmVyMRAwDgYDVQQKDAdWYW5oYWNrMR0wGwYDVQQLDBRTb2Z0d2FyZSBEZXZlbG9wbWVudDEQMA4GA1UEAwwHVmFuaGFjazEiMCAGCSqGSIb3DQEJARYTcmFwaGFlbEB2YW5oYWNrLmNvbTAeFw0xNjA4MjQxOTQzMzNaFw0yNjA4MjIxOTQzMzNaMIGjMQswCQYDVQQGEwJDQTEZMBcGA1UECAwQQnJpdGlzaCBDb2x1bWJpYTESMBAGA1UEBwwJVmFuY291dmVyMRAwDgYDVQQKDAdWYW5oYWNrMR0wGwYDVQQLDBRTb2Z0d2FyZSBEZXZlbG9wbWVudDEQMA4GA1UEAwwHVmFuaGFjazEiMCAGCSqGSIb3DQEJARYTcmFwaGFlbEB2YW5oYWNrLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANODmtpKbJIpPd8qVQRHzrCt6klivvHpyRuU0Z5HEbSptLRtmJIK9h/GM3PWfrGMbIdJWGD8ibf/DpEhvS7YT89YHpEjPOIi+hMp7yeVVfoKM5UBkBaXxQXJdrAWh7HMjtBqcLToQ9+YB4Vrz+68bm/MIjksqXzwO9yUP4xtPa/NKenRTO33IYLKlsche26P42z+L+DIJJbABaske94jt/JMLaZv+Pm18R8vJdvGDap1kONWFaWI4sDGHjvMP4qkWnBQtHpzhV6HUJVLKlGajS4pZ4dHtkGvYPEBLjVUpU2p5biGyPmtb7EQ6KAxzxZOz3T0si+G8bXNwzAvDldl1mkCAwEAAaNQME4wHQYDVR0OBBYEFCxfkqwjgp5JsVfcYKw9YztfVW5tMB8GA1UdIwQYMBaAFCxfkqwjgp5JsVfcYKw9YztfVW5tMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAG0syeSVV4DcShS83DLX2PxOP3emMLjXQQZNlgkfiTqIjoWGC/AXugadJMwmVu/v4jCE7+arIvdBqj9kIb5uQa1XTphjwYlc33Hsw2/rguqBL/rX2Yc9sVuuSMRD6I1bwG1t1A/xGJ05LRBUudC2LBRyJ6cM8zuisSA2owMxdNdy2aB9GyOdvLT8RYJjLvILehshM/bi4kdxU3Tcxd9/Oa59CWdjP5fx17QZPe9+TD2ndGN1pmQkw7HFQ8//vyquznJEI9rUADUXVTaArxmK6B4UQy2HaQ1kpFboePz+QVOT9nNf6X8dumvuDI7X6Oit7VcNgwx8nY6j4xZECk/8Oqs="));

            //string certificate = HttpContext.Current.Server.MapPath("~/phederal-cert-public.pem");

            //app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
            //{
            //    AllowedAudiences = new[] { "http://localhost:45204/resources" },
            //    TokenValidationParameters = new TokenValidationParameters
            //    {
            //        ValidAudience = "http://localhost:45204/resources",
            //        ValidIssuer = "http://localhost:45204/",
            //        IssuerSigningKey = new X509SecurityKey(new X509Certificate2(File.ReadAllBytes(certificate), "phederalapp"))
            //    }
            //});

            app.UseWebApi(config);
        }
Esempio n. 38
0
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.InboundClaimFilter = new HashSet <string>();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions()
            {
                AuthenticationMode = AuthenticationMode.Active,
                IssuerName         = Resources.IssuerNameUrl,
                SigningCertificate = new X509Certificate2(Resources.bulbacourses, "123"),
                ValidationMode     = ValidationMode.Local
            })
            .UseCors(new CorsOptions()
            {
                PolicyProvider = new CorsPolicyProvider()
                {
                    PolicyResolver = request => Task.FromResult(new CorsPolicy()
                    {
                        AllowAnyMethod = true,
                        AllowAnyHeader = true,
                        AllowAnyOrigin = true
                    })
                },
                CorsEngine = new CorsEngine()
            });
            Database.SetInitializer(new MigrateDatabaseToLatestVersion <AnalyticsContext, DAL.Migrations.Configuration>());
        }
Esempio n. 39
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = "https://localhost:44333/core",
                RequiredScopes = new[] { "api" },
                NameClaimType  = "name",
                RoleClaimType  = "role",

                // client credentials for the introspection endpoint
                ClientId     = "angularMaterial",
                ClientSecret = Guid.NewGuid().ToString()
            });

            var configuration = new HttpConfiguration();

            configuration.MapHttpAttributeRoutes();

            var jsonFormatter = configuration.Formatters.OfType <JsonMediaTypeFormatter>().FirstOrDefault();

            if (jsonFormatter != null)
            {
                jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            }

            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseWebApi(configuration);

            app.UseNancy();
            app.UseStageMarker(PipelineStage.MapHandler);
        }
Esempio n. 40
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = EndPointConstants.TokenServer,
                RequiredScopes = new[] { ResourceScopes.SecuredApi },
            });

            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            app.UseWebApi(config);

            config.EnableSwagger("docs/{apiVersion}/swagger", c =>
            {
                c.SingleApiVersion("v1", "Super duper API");

                var baseDirectory    = AppDomain.CurrentDomain.BaseDirectory;
                var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".XML";
                var commentsFile     = Path.Combine(baseDirectory, "bin", commentsFileName);
                c.IncludeXmlComments(commentsFile);
            });
        }
Esempio n. 41
0
        public void Configuration(IAppBuilder app)
        {
            // Allow all origins
            app.UseCors(CorsOptions.AllowAll);
            // Wire token validation
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = ConfigurationManager.AppSettings["IdentityProvider"],

                // For access to the introspection endpoint
                ClientId     = ConfigurationManager.AppSettings["IdentityClientId"],
                ClientSecret = ConfigurationManager.AppSettings["IdentityClientSecret"],

                RequiredScopes = new[] { "api", "profile", "email" }
            });

            // Wire Web API
            var config = new HttpConfiguration();

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.DependencyResolver       = new UnityResolver(UnityConfig.Get());
            //config.Filters.Add(new AuthorizeAttribute());
            //config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
            //            = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            WebApiConfig.Register(config);
            app.UseWebApi(config);
            var lserv = (LookupService)config.DependencyResolver.GetService(typeof(ILookupService));

            lserv.populateStaticIds();
        }
Esempio n. 42
0
 public void Configuration(IAppBuilder app)
 {
     // token validation
     app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
     {
         Authority = "https://localhost:44333/core"
     });
 }
Esempio n. 43
0
        public void Configuration(IAppBuilder app)
        {
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44300/idsvr",
                RequiredScopes = new[] { "write" }
            });

            // web api configuration
            app.UseWebApi(WebApiConfiguration());
        }
        public void Configuration(IAppBuilder app)
        {
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

            app.Use(async (context, next) =>
            {
                if (context.Request.Method != "OPTIONS" && context.Request.Cookies.Any())
                {
                    var cookie = context.Request.Cookies["Halo-Secure"];
                    if (!string.IsNullOrEmpty(cookie))
                    {
                        context.Request.Headers.Remove("Authorization");
                        context.Request.Headers.Add("Authorization", new[] { "Bearer " + cookie }); //.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", cookie.Cookies[0].Value);
                    }
                }

                await next.Invoke();
            });

            var corsPolicy = new CorsPolicy
            {
                AllowAnyMethod = true,
                AllowAnyHeader = true,
                AllowAnyOrigin = false,
                SupportsCredentials = true
            };
            corsPolicy.Origins.Add("http://localhost:32150");
            //corsPolicy.Origins.Add("https://localhost:32150");
            //corsPolicy.Origins.Add("http://localhost:32150/");
            //corsPolicy.Origins.Add("https://localhost:32150/");
            corsPolicy.ExposedHeaders.Add("X-Custom-Header");
            app.UseCors(new Microsoft.Owin.Cors.CorsOptions()
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(corsPolicy)
                }
            });

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
                {
                    Authority = "https://HFL0100:44333",
                    RequiredScopes = new[] { "api1" },
                    ValidationMode = ValidationMode.Local,
                    AuthenticationType = "Bearer",
                    AuthenticationMode = AuthenticationMode.Active,
            });
            // configure web api
            var config = new HttpConfiguration();
            config.Filters.Add(new AuthorizeAttribute());
            config.MapHttpAttributeRoutes();
            app.UseWebApi(config);
        }
Esempio n. 45
0
        public void Configuration(IAppBuilder app)
        {
            if (app.Properties.ContainsKey("AuthServer"))
            {
                //
                //IDsrv3 Section
                //
                var factory = InMemoryFactory.Create(
                                    scopes: Scopes.Get(),
                                    clients: Clients.Get(),
                                    users: Users.Get());

                var authenticationOptions = new AuthenticationOptions
                {

                    //RequireAuthenticatedUserForSignOutMessage = true,
                    //EnableSignOutPrompt = false,
                    //EnablePostSignOutAutoRedirect = true,
                    //PostSignOutAutoRedirectDelay = 0,

                };

                var options = new IdentityServerOptions
                {

                    AuthenticationOptions = authenticationOptions,
                    SigningCertificate = Certificate.Get(),
                    Factory = factory,
                    CorsPolicy = CorsPolicy.AllowAll,
                };

                app.UseIdentityServer(options);
            }
            else if (app.Properties.ContainsKey("ApiServer"))
            {
                //
                // api section
                //
                app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
                {
                    Authority = Constants.AuthorizationUrl,
                    RequiredScopes = new[] { "api1" }
                });

                //configure web api
                var config = new HttpConfiguration();
                EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
                config.EnableCors(cors);
                config.MapHttpAttributeRoutes();
                config.Filters.Add(new AuthorizeAttribute());
                app.UseWebApi(config);
            }
        }
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
                {
                    Authority = "https://localhost:44333/core",
                    RequiredScopes = new[] { "write" }
                });

            app.UseWebApi(WebApiConfig.Register());
        }
Esempio n. 47
0
 public void Configuration(IAppBuilder app)
 {
     app.UseIdentityServerBearerTokenAuthentication(new
     IdentityServerBearerTokenAuthenticationOptions
     {
         Authority = ExpenseTrackerConstants.IdSrv,
         RequiredScopes = new[] { "expensetrackerapi" }
     });
     
     app.UseWebApi(WebApiConfig.Register()); 
      
 }
Esempio n. 48
0
        public void Configuration(IAppBuilder app)
        {
            app.UseIdentityServerBearerTokenAuthentication(new Thinktecture.IdentityServer.AccessTokenValidation.IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44333/core",
                RequiredScopes = new string[] { "api1" }
            });

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Filters.Add(new AuthorizeAttribute());
            app.UseWebApi(config);
        }
Esempio n. 49
0
    public void Configuration(IAppBuilder app)
    {
      // token validation
      app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions() {
        Authority = ConfigurationManager.AppSettings["Is:Url"],
        RequiredScopes = new[] { "write"}
      });

      var config = new HttpConfiguration();
      WebApiConfig.Register(config);

      app.UseWebApi(config);
    }
Esempio n. 50
0
        public void Configuration(IAppBuilder app)
        {
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44300/identity",
                RequiredScopes = new[] { "gallerymanagement" }
            });

            // web api configuration
            var config = WebApiConfig.Register();

            app.UseWebApi(config);
        }
Esempio n. 51
0
        public void Configuration(IAppBuilder app)
        {
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://secured.local:449/identityserver/core",
                RequiredScopes = new [] { "api1" }
            });

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Filters.Add(new AuthorizeAttribute());
            app.UseWebApi(config);
        }
Esempio n. 52
0
        public void Configuration(IAppBuilder app)
        {
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44300/identity",
                RequiredScopes = new[] {"SampleApi"}
            });
            // web api configuration
            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();

            app.UseWebApi(config);
        }
Esempio n. 53
0
        public void Configuration(IAppBuilder app)
        {
            app.UseResourceAuthorization(new AuthorizationManager());

            var clientId = (string)ConfigurationManager.AppSettings["oauth2.clientid"];
            var authority = (string)ConfigurationManager.AppSettings["oauth2.authority"];

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

            app.UseResourceAuthorization(new AuthorizationManager());
        }
Esempio n. 54
0
 public void Configuration(IAppBuilder app)
 {
     try {
         string autority = ConfigurationManager.AppSettings["Authority"];
         IEnumerable<string> requiredScopes = ConfigurationManager.AppSettings["RequiredScopes"].Split(' ');
         app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions {
             Authority = autority,
             RequiredScopes = requiredScopes
         });
     }
     catch(Exception) {
         throw new ApplicationException("Os parâmetros de configuração da autenticação estão incorretos.");
     }
 }
        public static void Configuration(IAppBuilder app)
        {
            var idSrv = new IdentityServerStartup();
            idSrv.Configuration(app);

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            { 
                ValidationMode = ValidationMode.Local,
                IssuerName = "https://idsrv.acme.com",
                IssuerCertificate = Cert.Load()
            });
        }
Esempio n. 56
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = $"{SecurityConstants.IdentityServerUri}/identity",
                RequiredScopes = new[] { SecurityConstants.ApiScope },
                RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
            });

            var config = WebApiConfig.Register();
            app.UseWebApi(config);
        }
Esempio n. 57
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();
            var configurationService = new ConfigurationService();
#if DEBUG
            Log.Logger = new LoggerConfiguration()
                .WriteTo.Debug()
                .CreateLogger();

            config.Services.Add(typeof(IExceptionLogger), new DebugExceptionLogger());
#else
            Log.Logger = new LoggerConfiguration()
                .WriteTo.Elmah()
                .CreateLogger();
#endif
            // Autofac
            var builder = new ContainerBuilder();
            builder.Register(c => app.GetDataProtectionProvider()).InstancePerRequest();
            builder.Register(c => configurationService).As<ConfigurationService>().SingleInstance();
            builder.Register(c => configurationService.CurrentConfiguration).As<AppConfiguration>().SingleInstance();
            builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register(c => Log.Logger).As<ILogger>().SingleInstance();

            var container = AutofacBootstrapper.Initialize(builder, config);

            // Web API
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger());
            config.Filters.Add(new ElmahHandleErrorApiAttribute());
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver { IgnoreSerializableAttribute = true };

            app.UseIdentityServer(GetIdentityServerOptions(app, configurationService.CurrentConfiguration));

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = configurationService.CurrentConfiguration.SiteRoot,
                RequiredScopes = new[] { "api1" },
                ValidationMode = ValidationMode.ValidationEndpoint
            });

            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);

            app.UseClaimsTransformation(ClaimsTransformationOptionsFactory.Create());

            app.UseWebApi(config);
        }
Esempio n. 58
0
		public void Configuration(IAppBuilder app)
		{
			// token validation
			app.UseIdentityServerBearerTokenAuthentication(
				new IdentityServerBearerTokenAuthenticationOptions
				{
					Authority = IdealConstants.STSEndpoint,
					RequiredScopes = new[] { "sampleApi" }
				});

			// web api configuration
			var config = WebApiConfig.Register();

			app.UseWebApi(config);
		}
Esempio n. 59
0
        public void Configuration(IAppBuilder app)
        {
            //every request must contain token that matches below specification
            app.UseIdentityServerBearerTokenAuthentication(
                new IdentityServerBearerTokenAuthenticationOptions
             {
                 Authority = TripGallery.Constants.TripGallerySTS, //identity server url
                 RequiredScopes = new[] { "gallerymanagement" } //must match scope
             });

            var config = WebApiConfig.Register();

            app.UseWebApi(config);

            AutoMapperConfig.InitialiseMapping();
        }
Esempio n. 60
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
                {
                    Authority = "https://localhost:44333/core",
                    RequiredScopes = new[] { "write" },

                    // client credentials for the introspection endpoint
                    ClientId = "write",
                    ClientSecret = "secret"
                });

            app.UseWebApi(WebApiConfig.Register());
        }