private void ConfigureAuthorizerHttpClient(IServiceCollection services,
                                                   HttpClient client,
                                                   AuthorizerSetting settings,
                                                   CorsSetting corsSettings)
        {
            // access the DI container
            var serviceProvider = services.BuildServiceProvider();

            // Find the HttpContextAccessor service
            var httpContextAccessor = serviceProvider.GetService <IHttpContextAccessor>();

            // Get the bearer token from the request context (header)
            string bearerToken = null;

            bearerToken = httpContextAccessor.HttpContext.Request
                          .Headers["Authorization"]
                          .FirstOrDefault(h => h.StartsWith("bearer ", StringComparison.InvariantCultureIgnoreCase));

            // Add authorization if found
            if (bearerToken != null)
            {
                client.DefaultRequestHeaders.Add("Authorization", bearerToken);
            }

            // Add origin header
            if (corsSettings != null && corsSettings.AllowedOrigins.Length > 0)
            {
                client.DefaultRequestHeaders.Add("Origin", $"{httpContextAccessor.HttpContext.Request.Scheme}://{httpContextAccessor.HttpContext.Request.Host.Value}");
            }

            //Other Settings
            client.BaseAddress = new Uri($"{settings.Authority}/");
            client.DefaultRequestHeaders.Add("Accept", "application/x-www-form-urlencoded");
        }
Exemplo n.º 2
0
        public void InstallServices(IServiceCollection services, IConfiguration configuration)
        {
            //Set the AppSettings information
            var appSettingValues   = new AppSettings();
            var emailSettingValues = new EmailSetting();

            configuration.GetSection(nameof(AppSettings)).Bind(appSettingValues);
            configuration.GetSection(nameof(EmailSetting)).Bind(emailSettingValues);

            services.AddSingleton <AppSettings>(appSettingValues);
            services.AddSingleton <EmailSetting>(emailSettingValues);

            var authorizerSetting = new AuthorizerSetting();

            configuration.GetSection("Authorizer").Bind(authorizerSetting);

            if (!services.Any(x => x.ServiceType == typeof(AuthorizerSetting)))
            {
                services.AddSingleton(authorizerSetting);
            }

            //Handlers and Resources
            services.AddSingleton <IMessagesResourceHandler, MessagesResourceHandler>();
            services.AddSingleton <IMessageHandler, MessageHandler>();

            // Add application services.
            services.AddTransient <ISMTPEmailSender, SMTPEmailSender>();
            services.AddTransient <IRequestProvider, RequestProvider>();

            //User Profile
            services.AddScoped <IUserProfile, UserProfile>();
        }
        public void InstallServices(IServiceCollection services, IConfiguration configuration)
        {
            var authorizerSetting = new AuthorizerSetting();

            configuration.GetSection("Authorizer").Bind(authorizerSetting);

            if (!services.Any(x => x.ServiceType == typeof(AuthorizerSetting)))
            {
                services.AddSingleton(authorizerSetting);
            }

            var corsSetting = new CorsSetting();

            configuration.GetSection(nameof(CorsSetting)).Bind(corsSetting);

            if (!services.Any(x => x.ServiceType == typeof(CorsSetting)))
            {
                services.AddSingleton(corsSetting);
            }

            // http client services
            services.AddHttpClient("authorizer", c =>
            {
                ConfigureAuthorizerHttpClient(services, c, authorizerSetting, corsSetting);
            });
        }
        public void InstallServices(IServiceCollection services, IConfiguration configuration)
        {
            var authorizerSetting = new AuthorizerSetting();

            configuration.GetSection("Authorizer").Bind(authorizerSetting);

            if (!services.Any(x => x.ServiceType == typeof(AuthorizerSetting)))
            {
                services.AddSingleton(authorizerSetting);
            }

            //Antiforgery Setup
            services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN");

            //Add Culture
            var cultureInfo = new CultureInfo("es-PR");

            CultureInfo.DefaultThreadCurrentCulture   = cultureInfo;
            CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

            services.AddControllers();

            services.AddOptions();

            services.AddDistributedMemoryCache();

            //Authentication
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = authorizerSetting.Authority;
                options.ApiName              = authorizerSetting.ApiName;
                options.ApiSecret            = authorizerSetting.ApiSecret;
                options.EnableCaching        = true;
                options.CacheDuration        = TimeSpan.FromMinutes(authorizerSetting.CacheDuration);
                options.SupportedTokens      = SupportedTokens.Jwt;
                options.RequireHttpsMetadata = false;
            });

            services.AddMvcCore(options =>
            {
                var policy = ScopePolicy.Create("mipeapi.fullaccess");
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddAuthorization()
            .AddApiExplorer();
        }
Exemplo n.º 5
0
        public void InstallServices(IServiceCollection services, IConfiguration configuration)
        {
            var authorizerSetting = new AuthorizerSetting();

            configuration.GetSection("Authorizer").Bind(authorizerSetting);

            if (!services.Any(x => x.ServiceType == typeof(AuthorizerSetting)))
            {
                services.AddSingleton(authorizerSetting);
            }

            //Antiforgery Setup
            services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN");

            //Add Culture
            var cultureInfo = new CultureInfo("es-DO");

            CultureInfo.DefaultThreadCurrentCulture   = cultureInfo;
            CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

            services.AddControllers();

            services.AddOptions();

            services.AddDistributedMemoryCache();

            //Authentication
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = authorizerSetting.Authority;
                options.ApiName              = authorizerSetting.ApiName;
                options.ApiSecret            = authorizerSetting.ApiSecret;
                options.EnableCaching        = true;
                options.CacheDuration        = TimeSpan.FromMinutes(authorizerSetting.CacheDuration);
                options.SupportedTokens      = SupportedTokens.Jwt;
                options.RequireHttpsMetadata = false;

                options.JwtBearerEvents.OnTokenValidated = async(context) =>
                {
                    var identity = context.Principal.Identity as ClaimsIdentity;

                    var currentUsernameClaim = identity.Claims.FirstOrDefault(x => x.Type == "name");

                    if (currentUsernameClaim == null)
                    {
                        return;
                    }

                    // load user specific data from database (read cache too)
                    var cacheService = context.HttpContext.RequestServices.GetRequiredService <ICacheService>();

                    var claims = await cacheService.GetCachedAsync("SF_" + currentUsernameClaim.Value, async() =>
                    {
                        //var profileService = context.HttpContext.RequestServices.GetRequiredService<IProfileService>();

                        var profileClaims = new List <Claim>();

                        // TODO: Set the user profile claims here

                        return(profileClaims);
                    });

                    // add claims to the identity
                    identity.AddClaims(claims);
                };
            });

            services.AddMvcCore(options =>
            {
                var policy = ScopePolicy.Create("myboilerplate.fullaccess");
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddAuthorization(options =>
            {
                options.AddPolicy("ApiScope", policy =>
                {
                    policy.RequireAuthenticatedUser();
                    policy.RequireClaim("scope", "myboilerplateapi");
                });

                options.AddPolicy("ClientApplicationAccess", policy =>
                {
                    policy.Requirements.Add(new ClientApplicationAccessRequirement());
                });
            })
            .AddApiExplorer();

            // Handler that validates Client Access
            services.AddScoped <IAuthorizationHandler, ClientApplicationAccessAuthorizationHandler>();
        }