Exemplo n.º 1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            // use CORS policy
            app.UseCors("default");

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            IdentityServerAuthenticationOptions identityServerValidationOptions = new IdentityServerAuthenticationOptions
            {
                Authority             = "http://localhost:5000/",
                AllowedScopes         = { "webdatascope" },
                ApiSecret             = "XAWebDataSecret",
                ApiName               = "XAWebData",
                RequireHttpsMetadata  = false,
                AutomaticAuthenticate = true,
                SupportedTokens       = SupportedTokens.Both,
                // TokenRetriever = _tokenRetriever,
                // required if you want to return a 403 and not a 401 for forbidden responses
                AutomaticChallenge = true,
            };

            app.UseIdentityServerAuthentication(identityServerValidationOptions);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemplo n.º 2
0
        private static OAuth2IntrospectionOptions ConfigureIntrospection(IdentityServerAuthenticationOptions options)
        {
            var introspectionOptions = new OAuth2IntrospectionOptions
            {
                AuthenticationScheme = options.AuthenticationScheme,
                Authority            = options.Authority,
                ScopeName            = options.ScopeName,
                ScopeSecret          = options.ScopeSecret,

                AutomaticAuthenticate = options.AutomaticAuthenticate,
                AutomaticChallenge    = options.AutomaticChallenge,

                NameClaimType = options.NameClaimType,
                RoleClaimType = options.RoleClaimType,

                TokenRetriever     = _tokenRetriever,
                SaveTokensAsClaims = options.SaveTokensAsClaims,

                DiscoveryTimeout     = options.BackChannelTimeouts,
                IntrospectionTimeout = options.BackChannelTimeouts
            };

            if (options.IntrospectionBackChannelHandler != null)
            {
                introspectionOptions.IntrospectionHttpHandler = options.IntrospectionBackChannelHandler;
            }
            if (options.IntrospectionDiscoveryHandler != null)
            {
                introspectionOptions.DiscoveryHttpHandler = options.IntrospectionDiscoveryHandler;
            }

            return(introspectionOptions);
        }
Exemplo n.º 3
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseCors("corsGlobalPolicy");

            app.UseStaticFiles();

            IdentityServerAuthenticationOptions identityServerAuthenticationOptions = new IdentityServerAuthenticationOptions();

            identityServerAuthenticationOptions.Authority     = "https://localhost:44318/";
            identityServerAuthenticationOptions.AllowedScopes = new List <string> {
                "securedFiles"
            };
            identityServerAuthenticationOptions.ApiSecret             = "securedFilesSecret";
            identityServerAuthenticationOptions.ApiName               = "securedFiles";
            identityServerAuthenticationOptions.AutomaticAuthenticate = true;
            // required if you want to return a 403 and not a 401 for forbidden responses
            identityServerAuthenticationOptions.AutomaticChallenge = true;

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            app.UseIdentityServerAuthentication(identityServerAuthenticationOptions);

            app.UseMvc();
        }
Exemplo n.º 4
0
        private IdentityServerAuthenticationOptions GetIdentityOptions(IHostingEnvironment env)
        {
            var options = new IdentityServerAuthenticationOptions
            {
                AllowedScopes        = new string[] { "api" },
                RequireHttpsMetadata = env.IsProduction(),
                ApiName       = "api",
                NameClaimType = ClaimTypes.Email,
                // Version "2" until we retire the old jwt scheme and replace it with this one.
                AuthenticationScheme = "Bearer2",
                TokenRetriever       = TokenRetrieval.FromAuthorizationHeaderOrQueryString("Bearer2", "access_token2")
            };

            if (env.IsProduction())
            {
                options.Authority = "https://api.bitwarden.com";
            }
            else if (env.IsEnvironment("Preview"))
            {
                options.Authority = "https://preview-api.bitwarden.com";
            }
            else
            {
                options.Authority = "http://localhost:4000";
                //options.Authority = "http://169.254.80.80:4000"; // for VS Android Emulator
                //options.Authority = "http://192.168.1.8:4000"; // Desktop external
            }

            return(options);
        }
Exemplo n.º 5
0
        private static IdentityServerAuthenticationOptions ToIdentityOptions(this IConfiguration configuration)
        {
            var identityOptions = new IdentityServerAuthenticationOptions();

            configuration.Bind(identityOptions);
            return(identityOptions);
        }
Exemplo n.º 6
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();

            app.UseExceptionHandler("/Home/Error");
            app.UseCors("corsGlobalPolicy");
            app.UseStaticFiles();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            IdentityServerAuthenticationOptions identityServerValidationOptions = new IdentityServerAuthenticationOptions
            {
                Authority     = "https://localhost:44318/",
                AllowedScopes = new List <string> {
                    "dataEventRecords"
                },
                ApiSecret             = "dataEventRecordsSecret",
                ApiName               = "dataEventRecords",
                AutomaticAuthenticate = true,
                SupportedTokens       = SupportedTokens.Both,
                // TokenRetriever = _tokenRetriever,
                // required if you want to return a 403 and not a 401 for forbidden responses
                AutomaticChallenge = true,
            };

            app.UseIdentityServerAuthentication(identityServerValidationOptions);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        private TestServer CreateRegistrationApiTestServer(string storageProvider)
        {
            var options = new IdentityServerAuthenticationOptions
            {
                Authority                       = IdentityServerUrl,
                ApiName                         = RegistrationApiName,
                RequireHttpsMetadata            = false,
                JwtBackChannelHandler           = IdentityTestServer.CreateHandler(),
                IntrospectionBackChannelHandler = IdentityTestServer.CreateHandler(),
                IntrospectionDiscoveryHandler   = IdentityTestServer.CreateHandler()
            };

            var hostingOptions = new HostingOptions
            {
                UseIis          = false,
                UseTestUsers    = true,
                StorageProvider = storageProvider
            };

            var apiBuilder = new WebHostBuilder();

            apiBuilder.ConfigureServices(c => c.AddSingleton(LdapSettings)
                                         .AddSingleton(options)
                                         .AddSingleton(CouchDbSettings)
                                         .AddSingleton(hostingOptions)
                                         .AddSingleton(ConnectionStrings)
                                         );

            apiBuilder.UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup <Startup>()
            .UseUrls(RegistrationApiServerUrl);

            return(new TestServer(apiBuilder));
        }
Exemplo n.º 8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions <AuthServerSettings> authSettings)
        {
            loggerFactory.AddSerilog();

            app.UseCors("corsGlobalPolicy");

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            IdentityServerAuthenticationOptions identityServerValidationOptions = new IdentityServerAuthenticationOptions
            {
                Authority             = authSettings.Value?.BaseUrl,
                AutomaticAuthenticate = true,
                AllowedScopes         = new List <string>()
                {
                    "accountService"
                },
                ApiSecret          = "accountServiceSecret",
                ApiName            = "accountService",
                SupportedTokens    = SupportedTokens.Both,
                AutomaticChallenge = true,
            };

            app.UseIdentity();
            app.UseIdentityServerAuthentication(identityServerValidationOptions);
            app.UseMvc();
        }
Exemplo n.º 9
0
        public override void BindIdentityServerAuthenticationOptions(IdentityServerAuthenticationOptions options)
        {
            base.BindIdentityServerAuthenticationOptions(options);

            options.JwtBackChannelHandler           = IdpHandler;
            options.IntrospectionBackChannelHandler = IdpHandler;
            options.IntrospectionDiscoveryHandler   = IdpHandler;
        }
Exemplo n.º 10
0
 void Options(IdentityServerAuthenticationOptions o)
 {
     o.Authority            = Configuration[AppSettingKeys.Authority];
     o.RequireHttpsMetadata = Configuration.GetValue <bool>(AppSettingKeys.RequireHttpsMetadata);
     o.SupportedTokens      = SupportedTokens.Both;
     o.ApiSecret            = Configuration[AppSettingKeys.ApiSecret];
     o.ApiName = Configuration[AppSettingKeys.ApiName];
 }
Exemplo n.º 11
0
        public static IApplicationBuilder UseIdentityServerAuthentication(this IApplicationBuilder app, Action <IdentityServerAuthenticationOptions> configureOptions)
        {
            var options = new IdentityServerAuthenticationOptions();

            configureOptions(options);

            return(app.UseIdentityServerAuthentication(options));
        }
Exemplo n.º 12
0
 public PermissionStoreHttpHandler(ILogger <PermissionStoreHttpHandler> logger,
                                   IOptionsMonitor <IdentityServerAuthenticationOptions> optionsMonitor,
                                   IHttpClientFactory httpClientFactory)
 {
     _logger            = logger;
     _httpClientFactory = httpClientFactory;
     _options           = optionsMonitor.Get("Bearer");
 }
Exemplo n.º 13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddFile("Logs/myapp-{Date}.txt", LogLevel.Debug);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseCors("default");
            app.UseIdentityServer();
            app.UseStaticFiles();


            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                RequireHttpsMetadata = false,
                Authority            = Config.ApiAuthority,
                Audience             = "api"
            });

            var authenticationOptions = new IdentityServerAuthenticationOptions
            {
                RequireHttpsMetadata = false,
                Authority            = Config.ApiAuthority,
                AllowedScopes        = { "api" },
            };
            var tokenRetriever = authenticationOptions.TokenRetriever;

            authenticationOptions.TokenRetriever = (req) => {
                string authHeaderToken = tokenRetriever(req);
                if (authHeaderToken != null)
                {
                    return(authHeaderToken);
                }
                StringValues queryTokenValues;
                if (req.Query.TryGetValue("access_token", out queryTokenValues))
                {
                    string queryToken = queryTokenValues.LastOrDefault();
                    return(queryToken);
                }
                ;
                return(null);
            };
            app.UseIdentityServerAuthentication(authenticationOptions);


            app.UseWebSockets();
            app.MapWebSocketManager("/chat", serviceProvider.GetService <ChatHandler>());

            app.UseMvc();
        }
Exemplo n.º 14
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseCors("corsGlobalPolicy");

            app.UseStaticFiles();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            var identityServerValidationOptions = new IdentityServerAuthenticationOptions
            {
                Authority     = env.IsDevelopment() ? "https://localhost:44348/" : "https://localhost/IdentityProvider",
                AllowedScopes = new List <string> {
                    "wanvet"
                },
                ApiSecret             = "wanvetSecret",
                ApiName               = "wanvet",
                AutomaticAuthenticate = true,
                SupportedTokens       = SupportedTokens.Both,
                AutomaticChallenge    = true,
            };

            app.UseIdentityServerAuthentication(identityServerValidationOptions);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();

                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement = true,
                    ConfigFile           = "config/webpack.config.js"
                });

                // NOTE: For SPA swagger needs adding before MVC
                // Enable middleware to serve generated Swagger as a JSON endpoint
                app.UseSwagger();

                // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
                app.UseSwaggerUi();
            }


            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
        }
Exemplo n.º 15
0
        private void ConfigureAuthentication(IdentityServerAuthenticationOptions options)
        {
            var authenticationServerUrl = Configuration["AuthorizationServer:Authority"];

            options.Authority            = authenticationServerUrl;
            options.RequireHttpsMetadata = false;
            options.ApiName         = "web_app";
            options.ApiSecret       = "secret";
            options.SupportedTokens = SupportedTokens.Reference;
        }
Exemplo n.º 16
0
        public static IdentityServerAuthenticationOptions GetServerAutentication(IdentityServerAuthenticationOptions options)
        {
            options.ApiName              = _config.ClientId;
            options.Authority            = _config.AuthUrl;
            options.RequireHttpsMetadata = false; // only for development
            options.ApiSecret            = _config.Secret;
            options.SupportedTokens      = SupportedTokens.Both;

            return(options);
        }
Exemplo n.º 17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            app.UseApplicationInsightsRequestTelemetry();
            app.UseApplicationInsightsExceptionTelemetry();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentity();

            app.UseIdentity();

            app.UseIdentityServer();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            var SSOAuthority = "http://localhost:50447";
            var identityServerValidationOptions = new IdentityServerAuthenticationOptions
            {
                Authority             = SSOAuthority,
                ScopeName             = "client",
                ScopeSecret           = "secret",
                AutomaticAuthenticate = true,
                RequireHttpsMetadata  = false,
                SupportedTokens       = SupportedTokens.Both,
                // required if you want to return a 403 and not a 401 for forbidden responses
                AutomaticChallenge = true
            };

            app.UseIdentityServerAuthentication(identityServerValidationOptions);

            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areaRoute",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemplo n.º 18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //Setup logging
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            //Allow CORS
            app.UseCors(CorsPolicyName);

            //Disable default mapping for JWT
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            //Setup Auth Server
            var identityServerValidationOptions = new IdentityServerAuthenticationOptions
            {
                Authority     = AuthAuthorityUriHttps,
                AllowedScopes = new List <string> {
                    "spaApi"
                },                                             //,"spaScope", "spa.user","spa.admin"
                ApiSecret             = "spaSecret",
                ApiName               = "spaApi",
                AutomaticAuthenticate = true,
                SupportedTokens       = SupportedTokens.Both,
                // TokenRetriever = _tokenRetriever,
                // required if you want to return a 403 and not a 401 for forbidden responses
                AutomaticChallenge = true,
                //RequireHttpsMetadata = false
            };

            app.UseIdentityServerAuthentication(identityServerValidationOptions);



            //Swashbuckle Configuration
            app.UseSwagger();
            app.UseSwaggerUi(c =>
            {
                c.ConfigureOAuth2(SwaggerClientName, "", "", SwaggerClientName, additionalQueryStringParameters: new {
                    redirect_uri = SwaggerRedirectUriHttps
                });

                c.SwaggerEndpoint(SwaggerEndpoint, SwaggerDescription);
            });

            //Migrate to latest and run seeding logic
            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetService <SpaContext>();
                context.Database.Migrate();
                context.EnsureSeedData();
            }

            app.UseMvc();
        }
        public static void ConfigureIdentityServerAuthentication(IdentityServerAuthenticationOptions identityServerAuthenticationOptions)
        {
            var identityServerAuthenticationConfiguration = new IdentityServerAuthenticationConfiguration();

            _configuration.GetSection(nameof(IdentityServerAuthenticationConfiguration)).Bind(identityServerAuthenticationConfiguration);

            identityServerAuthenticationOptions.Authority            = identityServerAuthenticationConfiguration.Authority;
            identityServerAuthenticationOptions.ApiName              = identityServerAuthenticationConfiguration.ApiName;
            identityServerAuthenticationOptions.ApiSecret            = identityServerAuthenticationConfiguration.ApiSecret;
            identityServerAuthenticationOptions.EnableCaching        = identityServerAuthenticationConfiguration.EnableCaching;
            identityServerAuthenticationOptions.RequireHttpsMetadata = identityServerAuthenticationConfiguration.RequireHttpsMetadata;
            identityServerAuthenticationOptions.SupportedTokens      = identityServerAuthenticationConfiguration.SupportedTokens;
        }
Exemplo n.º 20
0
        private IdentityServerAuthenticationOptions GetIdentityOptions(IHostingEnvironment env,
                                                                       GlobalSettings globalSettings, string suffix)
        {
            var options = new IdentityServerAuthenticationOptions
            {
                Authority            = globalSettings.BaseServiceUri.InternalIdentity,
                AllowedScopes        = new string[] { "api", "api.push", "api.licensing" },
                RequireHttpsMetadata = !env.IsDevelopment() && globalSettings.BaseServiceUri.InternalIdentity.StartsWith("https"),
                NameClaimType        = ClaimTypes.Email,
                // Suffix until we retire the old jwt schemes.
                AuthenticationScheme = $"Bearer{suffix}",
                TokenRetriever       = TokenRetrieval.FromAuthorizationHeaderOrQueryString($"Bearer{suffix}", $"access_token{suffix}")
            };

            return(options);
        }
Exemplo n.º 21
0
        private static JwtBearerOptions ConfigureJwt(IdentityServerAuthenticationOptions options)
        {
            var jwtOptions = new JwtBearerOptions
            {
                AuthenticationScheme = options.AuthenticationScheme,
                Authority            = options.Authority,
                RequireHttpsMetadata = false,

                AutomaticAuthenticate = options.AutomaticAuthenticate,
                AutomaticChallenge    = options.AutomaticChallenge,

                BackchannelTimeout         = options.BackChannelTimeouts,
                RefreshOnIssuerKeyNotFound = true,

                Events = new JwtBearerEvents
                {
                    OnReceivingToken = e =>
                    {
                        e.Token = _tokenRetriever(e.Request);

                        return(Task.FromResult(0));
                    },
                    OnValidatedToken = e =>
                    {
                        if (options.SaveTokensAsClaims)
                        {
                            e.AuthenticationTicket.Principal.Identities.First().AddClaim(
                                new Claim("access_token", _tokenRetriever(e.Request)));
                        }

                        return(Task.FromResult(0));
                    }
                }
            };

            if (options.JwtBackChannelHandler != null)
            {
                jwtOptions.BackchannelHttpHandler = options.JwtBackChannelHandler;
            }

            jwtOptions.TokenValidationParameters.ValidateAudience = false;
            jwtOptions.TokenValidationParameters.NameClaimType    = options.NameClaimType;
            jwtOptions.TokenValidationParameters.RoleClaimType    = options.RoleClaimType;

            return(jwtOptions);
        }
Exemplo n.º 22
0
        public IdentityServerAuthenticationOptions GetIdentityServerAuthenticationOptions(string authenticationScheme = "API")
        {
            var options = new IdentityServerAuthenticationOptions
            {
                Authority                       = "http://localhost",
                RequireHttpsMetadata            = false,
                JwtBackChannelHandler           = _identityServer.CreateHandler(),
                IntrospectionBackChannelHandler = _identityServer.CreateHandler(),
                IntrospectionDiscoveryHandler   = _identityServer.CreateHandler(),
                //AutomaticAuthenticate = true,
                //AuthenticationScheme = authenticationScheme,
                ApiName   = _apiName,
                ApiSecret = _apiSecret
            };

            return(options);
        }
Exemplo n.º 23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            /* Setting up dependency injection */

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddTransient <ILogger <TransactionController>, Logger <TransactionController> >();

            // In-memory DbContext
            services.AddDbContext <PaymentDbContext>(options =>
            {
                options
                .UseInMemoryDatabase("Payment")
                .ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning));
            });

            // Identity Server
            services
            .AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                var settings = new IdentityServerAuthenticationOptions();

                Configuration.Bind("IdentityServerSettings", settings);

                options.Authority            = settings.Authority;
                options.RequireHttpsMetadata = settings.RequireHttpsMetadata;
                options.ApiName   = settings.ApiName;
                options.ApiSecret = settings.ApiSecret;
            });

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info {
                    Title = "RothschildHouse API", Version = "v1"
                });

                // Get xml comments path
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

                // Set xml path
                options.IncludeXmlComments(xmlPath);
            });
        }
Exemplo n.º 24
0
        private void RegisterRegistrationServices(IWebHostBuilder builder)
        {
            var options = new IdentityServerAuthenticationOptions
            {
                Authority                       = IdentityServerUrl,
                ApiName                         = RegistrationApiName,
                RequireHttpsMetadata            = false,
                JwtBackChannelHandler           = IdentityTestServer.CreateHandler(),
                IntrospectionBackChannelHandler = IdentityTestServer.CreateHandler(),
                IntrospectionDiscoveryHandler   = IdentityTestServer.CreateHandler()
            };

            builder.ConfigureServices(c => c.AddSingleton(options)
                                      .AddSingleton <IPostConfigureOptions <JwtBearerOptions> >(new PostConfigureOptions <JwtBearerOptions>("Bearer", jwtOpts =>
            {
                jwtOpts.BackchannelHttpHandler = new SuppressExecutionContextHandler(IdentityTestServer.CreateHandler());
            })));
        }
Exemplo n.º 25
0
        private IdentityServerAuthenticationOptions GetIdentityOptions(IHostingEnvironment env,
                                                                       string authority, string suffix)
        {
            var options = new IdentityServerAuthenticationOptions
            {
                Authority            = authority,
                AllowedScopes        = new string[] { "api" },
                RequireHttpsMetadata = env.IsProduction(),
                ApiName       = "api",
                NameClaimType = ClaimTypes.Email,
                // Suffix until we retire the old jwt schemes.
                AuthenticationScheme = $"Bearer{suffix}",
                TokenRetriever       = TokenRetrieval.FromAuthorizationHeaderOrQueryString(
                    $"Bearer{suffix}", $"access_token{suffix}")
            };

            return(options);
        }
        public void FindSingletonImplementationInstance()
        {
            //Given
            var service = new IdentityServerAuthenticationOptions {
                ApiName = "Test"
            };
            var services = new ServiceCollection();

            services.AddSingleton(new object());
            services.AddSingleton(new List <string>());
            services.AddSingleton(service);
            services.AddSingleton(new HashSet <string>());

            //When
            var foundService = services.FindSingletonImplementationInstance <IdentityServerAuthenticationOptions>();

            //Then
            Assert.NotNull(foundService);
            Assert.Same(service, foundService);
        }
Exemplo n.º 27
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            app.UseApplicationInsightsExceptionTelemetry();

            var options = new IdentityServerAuthenticationOptions
            {
                Authority            = "http://localhost:5297",
                RequireHttpsMetadata = false,
                ApiName = "TetrisApi"
            };

            app.UseIdentityServerAuthentication(options);

            app.UseMvc();
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseCors("corsGlobalPolicy");

            app.UseStaticFiles();

            IdentityServerAuthenticationOptions identityServerAuthenticationOptions = new IdentityServerAuthenticationOptions();
            identityServerAuthenticationOptions.Authority = "https://localhost:44318/";
            identityServerAuthenticationOptions.AllowedScopes = new List<string> { "securedFiles" };
            identityServerAuthenticationOptions.ApiSecret = "securedFilesSecret";
            identityServerAuthenticationOptions.ApiName = "securedFiles";
            identityServerAuthenticationOptions.AutomaticAuthenticate = true;
            // required if you want to return a 403 and not a 401 for forbidden responses
            identityServerAuthenticationOptions.AutomaticChallenge = true;

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            app.UseIdentityServerAuthentication(identityServerAuthenticationOptions);

            app.UseMvc();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            /* Configuration for MVC */

            services
            .AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });

            /* Setting dependency injection */

            // For DbContext
            services.AddDbContext <OnlineStoreDbContext>(builder =>
            {
                builder.UseSqlServer(Configuration["ConnectionStrings:OnlineStore"]);
            });

            // User info
            services.AddScoped <IUserInfo, UserInfo>();

            // Logger for services
            services.AddScoped <ILogger, Logger <Service> >();

            /* Identity Server for Online Store */

            services.Configure <OnlineStoreIdentityClientSettings>(Configuration.GetSection("OnlineStoreIdentityClientSettings"));
            services.AddSingleton <OnlineStoreIdentityClientSettings>();

            /* Rothschild House Payment gateway */
            services.Configure <RothschildHouseIdentitySettings>(Configuration.GetSection("RothschildHouseIdentitySettings"));
            services.AddSingleton <RothschildHouseIdentitySettings>();

            services.Configure <RothschildHousePaymentSettings>(Configuration.GetSection("RothschildHousePaymentSettings"));
            services.AddSingleton <RothschildHousePaymentSettings>();

            services.AddScoped <IRothschildHouseIdentityClient, RothschildHouseIdentityClient>();
            services.AddScoped <IRothschildHousePaymentClient, RothschildHousePaymentClient>();

            /* Online Store Services */
            services.AddScoped <IHumanResourcesService, HumanResourcesService>();
            services.AddScoped <IWarehouseService, WarehouseService>();
            services.AddScoped <ISalesService, SalesService>();

            /* Configuration for authorization */

            services
            .AddMvcCore()
            .AddAuthorization(options =>
            {
                options
                .AddPolicy(Policies.AdministratorPolicy, builder => builder.Requirements.Add(new AdministratorPolicyRequirement()));

                options
                .AddPolicy(Policies.WarehouseManagerPolicy, builder => builder.Requirements.Add(new WarehouseManagerPolicyRequirement()));

                options
                .AddPolicy(Policies.WarehouseOperatorPolicy, builder => builder.Requirements.Add(new WarehouseOperatorPolicyRequirement()));

                options
                .AddPolicy(Policies.CustomerPolicy, builder => builder.Requirements.Add(new CustomerPolicyRequirement()));
            });

            /* Configuration for Identity Server authentication */

            services
            .AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                var settings = new IdentityServerAuthenticationOptions();

                Configuration.Bind("IdentityServerSettings", settings);

                options.Authority            = settings.Authority;
                options.RequireHttpsMetadata = settings.RequireHttpsMetadata;
                options.ApiName   = settings.ApiName;
                options.ApiSecret = settings.ApiSecret;
            });

            /* Configuration for Help page */

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info {
                    Title = "Online Store API", Version = "v1"
                });

                // Get xml comments path
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

                // Set xml path
                options.IncludeXmlComments(xmlPath);
            });
        }
Exemplo n.º 30
0
        public static IdentityServerAuthenticationOptions GetDefaultAuthenticationOptions(IdentityServerAuthenticationOptions options)
        {
            options.Authority            = "http://localhost:5001";
            options.RequireHttpsMetadata = false;

            options.ApiName = "api1";

            return(options);
        }
 public virtual void BindIdentityServerAuthenticationOptions(IdentityServerAuthenticationOptions options)
 {
     Configuration.GetSection("IdentityProvider").Bind(options);
 }