Exemple #1
0
 protected override IMvcCoreBuilder ConfigureMvc(IMvcCoreBuilder builder)
 {
     return(builder.AddApiExplorer()
            .AddAuthorization()
            .AddCacheTagHelper()
            .AddCookieTempDataProvider()
            .AddDataAnnotations()
            .AddModelValidator()
            .AddRazorPages()
            .AddRazorViewEngine()
            .AddViews()
            .AddCors(
                options => options.AddDefaultPolicy(
                    configure =>
     {
         options.DefaultPolicyName = this.Options.ApiScope;
         configure.AllowAnyHeader()
         .AllowAnyMethod()
         .AllowAnyOrigin()
         .AllowCredentials();
     }))
            .AddMvcOptions(
                options =>
     {
         var policy = ScopePolicy.Create(this.Options.ApiScope);
         options.Filters.Add(new AuthorizeFilter(policy));
     }));
 }
Exemple #2
0
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddAuthorization(options =>
                {
                    options.AddPolicy("AssertScope", policy =>
                                      policy.RequireClaim("scope", "esw.toolingInt"));

                    options.AddPolicy("AssertTestScope", policy =>
                                      policy.RequireClaim("scope", "esw.toolingIntTest"));
                });

                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddIdentityServerAuthentication(
                    x =>
                {
                    x.ApiName   = "esw.toolingIntTest";
                    x.Authority = "https://security-sts.ci.eshopworld.net";
                });

                services.AddMvc(options =>
                {
                    var policy = ScopePolicy.Create("esw.toolingInt");
                    options.Filters.Add(new AuthorizeFilter(policy));
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

                services.AddLogging();
                services.Add(new ServiceDescriptor(typeof(IBigBrother), Mock.Of <IBigBrother>()));
            }
        public static IServiceCollection AddSecurity(this IServiceCollection services, IConfiguration configuration)
        {
            var identityOptions = configuration.ToIdentityOptions();

            services.AddSingleton(identityOptions);
            if (string.IsNullOrEmpty(identityOptions.Authority))
            {
                return(services);
            }

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(configuration.Bind);

            services.Configure <MvcOptions>(x => x.Filters.Add(new AuthorizeFilter(ScopePolicy.Create(identityOptions.ApiName))));

            services.ConfigureSwaggerGen(options =>
            {
                options.AddSecurityDefinition("oauth2-implicit", new OAuth2Scheme
                {
                    Type             = "oauth2",
                    Flow             = "implicit",
                    AuthorizationUrl = $"{identityOptions.Authority}/connect/authorize",
                    Scopes           = new Dictionary <string, string>
                    {
                        [identityOptions.ApiName] = "Use the app."
                    }
                });
                options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    ["oauth2-implicit"] = new string[0]
                });
            });

            return(services);
        }
Exemple #4
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore(options =>
            {
                var policy = ScopePolicy.Create("api1", "openid");     // "api1", "openid", "offline_access"
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddAuthorization()
            .AddJsonFormatters();

            // https://github.com/IdentityServer/IdentityServer4.AccessTokenValidation
            // id services
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            // Supporting reference tokens
            //IdentityServerAuthenticationOptions
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority                = Authority;
                options.SupportedTokens          = SupportedTokens.Both; // jwt and reference
                options.LegacyAudienceValidation = true;                 // if you need to support both JWTs and reference token
                options.RequireHttpsMetadata     = false;
                options.ApiName       = "api1";
                options.ApiSecret     = "secret";
                options.RoleClaimType = ClaimTypes.Role;     // override standard JwtClaimTypes.Role
                options.EnableCaching = false;
            });
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore(options =>
            {
                // required scopes
                var policy = ScopePolicy.Create("api1");
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddAuthorization()
            .AddJsonFormatters();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                // base-address of your identityserver
                options.Authority = "http://localhost:5000";

                // name of the API resource
                options.ApiName              = "api1";
                options.ApiSecret            = "secretapi";
                options.RequireHttpsMetadata = false;
            });

            services.AddCors(options =>
            {
                // this defines a CORS policy called "default"
                options.AddPolicy("default", policy =>
                {
                    policy.WithOrigins("http://localhost:5003")
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });
        }
 /// <summary>
 /// Adds authorization policies for all scopes discovered provided by <see cref="ScopeAuthorizeAttribute.GetAllScopes"/>.
 /// </summary>
 public static void AddScopePolicies(this AuthorizationOptions options)
 {
     foreach (string scope in ScopeAuthorizeAttribute.GetAllScopes())
     {
         options.AddPolicy(scope, ScopePolicy.Create(scope));
     }
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(options =>
            {
                var policy = ScopePolicy.Create("strata.api");
                options.Filters.Add(new AuthorizeFilter(policy));
            });

            services.Configure <CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded    = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.All;
                options.KnownNetworks.Clear();
                options.KnownProxies.Clear();
            });

            services.AddHttpsRedirection(options =>
            {
                options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
                options.HttpsPort          = 443;
            });

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://localhost:8471";
                options.SaveToken = true;
                options.ApiName   = "api";
            });
            //.AddJwtBearer("Bearer", options =>
            //{
            //    options.Authority = "https://localhost:8471";

            //    options.TokenValidationParameters = new TokenValidationParameters
            //    {
            //        ValidateAudience = false
            //    };
            //});

            services.AddAuthorization(options =>
            {
                options.AddPolicy("ApiScope", policy =>
                {
                    policy.RequireAuthenticatedUser();
                    policy.AuthenticationSchemes.Add(IdentityServerAuthenticationDefaults.AuthenticationScheme);
                    policy.RequireClaim("scope", "strata.api");
                });
            });

            services.AddHttpClient();
            services.AddOptions();
            services.AddTransient <ForexServiceClientOptions>();
            services.AddTransient <IForexServiceClient, ForexServiceClient>();
        }
        public static void AddAuthorizeFilter(this MvcOptions options, [CanBeNull] IConfiguration authenticationConfiguration)
        {
            var identityOptions = authenticationConfiguration?.ToIdentityOptions();

            if (string.IsNullOrEmpty(identityOptions?.Authority))
            {
                return;
            }

            options.Filters.Add(new AuthorizeFilter(ScopePolicy.Create(identityOptions.ApiName + ".api")));
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                config.Filters.Add(new AuthorizeFilter(policy)); //global authorize filter


                // require scope1 or scope2
                var policyc = ScopePolicy.Create("merhabain");
                config.Filters.Add(new AuthorizeFilter(policyc));
            })
            .AddAuthorization(options =>
                              //TODO Blocks values controlle one api but did not let to use
                              options.AddPolicy("jsclient", config =>
            {
                config.AddAuthenticationSchemes("bearer");
                config.RequireClaim("client_id", "spa");
            })
                              )
            .AddJsonFormatters();

            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = "http://localhost:5000";
                options.RequireHttpsMetadata = false;

                options.ApiName = "verywon-dbservice";

                options.EnableCaching = true;
                options.CacheDuration = TimeSpan.FromMinutes(10);
            });

            services.AddCors(options =>
            {
                // this defines a CORS policy called "default"
                options.AddPolicy("default", policy =>
                {
                    policy.WithOrigins("http://localhost:5100")
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            services.AddDbContext <ServiceTContext>(
                options =>
                options.UseNpgsql(Configuration.GetConnectionString("PostgreConnection"))
                );

            // services.AddScoped<IGenericRepostitory, ProductRepository>();
        }
Exemple #10
0
 protected override IMvcCoreBuilder ConfigureMvc(IMvcCoreBuilder builder)
 {
     return(builder.AddCacheTagHelper()
            .AddCookieTempDataProvider()
            .AddDataAnnotations()
            .AddModelValidator()
            .AddRazorPages()
            .AddRazorViewEngine()
            .AddViews()
            .AddMvcOptions(
                options =>
     {
         var policy = ScopePolicy.Create(this.Options.ApiScope);
         options.Filters.Add(new AuthorizeFilter(policy));
     }));
 }
        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();
        }
Exemple #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var corsBuilder = new CorsPolicyBuilder();

            corsBuilder.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowAnyOrigin()
            .AllowCredentials();

            services.AddCors(options =>
            {
                options.AddPolicy("MyCorsPolicy", corsBuilder.Build());
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("MyCorsPolicy"));
            });


            services
            .AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = "http://216.69.181.183/IdentityServer/";
                options.RequireHttpsMetadata = false;
                options.ApiName       = "api1";
                options.NameClaimType = "user_name";
                options.RoleClaimType = "role";
                //options.typ
                //options.
            });

            services
            .AddMvcCore(options =>
            {
                // require scope1 or scope2
                var policy = ScopePolicy.Create("openid", "profile");
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddAuthorization()
            .AddJsonFormatters();
            _MigrateDataBase();
        }
Exemple #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(opts =>
            {
                var policy = ScopePolicy.Create("core.api");
                opts.Filters.Add(new AuthorizeFilter(policy));
            });

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "http://localhost:5000";
                options.ApiName   = "api1";

                options.EnableCaching = true;
                options.CacheDuration = TimeSpan.FromMinutes(10);
            });
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddMvcCore()
            .AddAuthorization(options =>
            {
                options.AddPolicy("write_access", ScopePolicy.Create("userapi.write_access"));
            })
            .AddJsonFormatters();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = "http://localhost:5000";
                options.ApiName              = "userapi";
                options.RequireHttpsMetadata = false;
            });
        }
Exemple #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                // base-address of your identityserver
                options.Authority            = "http://localhost:5000";
                options.RequireHttpsMetadata = false;
                // name of the API resource
                options.ApiName = "api1";
            });

            services.AddAuthorization(opt =>
            {
                opt.AddPolicy("fullAccess",
                              builder =>
                {
                    builder.RequireScope("api1.read_only");
                    builder.RequireScope("api1.full_access");
                });

                // opt.AddPolicy("somehting", builder =>
                // {
                //     builder.RequireScope()
                // });
                //
                // opt.AddPolicy();
                //
                // IAuthorizationRequirement
                // var abc = new AuthorizationPolicy();
            });

            services.AddControllers(opt =>
            {
                var policy = ScopePolicy.Create("api1.full_access");
                opt.Filters.Add(new AuthorizeFilter(policy));
            });
        }
Exemple #16
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore(options =>
            {
                // IS3 does not include the api name/audience - hence the extra scope check
                options.Filters.Add(new AuthorizeFilter(ScopePolicy.Create("api")));
            })
            .AddAuthorization();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = "http://localhost:5002";
                options.RequireHttpsMetadata = false;

                options.ApiName   = "api";
                options.ApiSecret = "secret";

                // this is only needed because IS3 does not include the API name in the JWT audience list
                // so we disable UseIdentityServerAuthentication JWT audience check and rely upon
                // scope validation to ensure we're only accepting tokens for the right API
                options.LegacyAudienceValidation = true;
            });
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(AllowedOrigins,
                                  builder =>
                {
                    builder
                    .WithOrigins("http://localhost:3000")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithExposedHeaders("X-Pagination", "Access-Control-Allow-Origin");
                });
            });
            services.AddDbContext <ApiDbContext>(options =>
                                                 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddMvcCore(options =>
            {
                var policy = ScopePolicy.Create("bapi");
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver())
            .AddAuthorization()
            .AddJsonFormatters()
            .AddDataAnnotations()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return(factory.Create("SharedResource", assemblyName.Name));
                };
            });

            services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options =>
            {
                options.Authority            = "http://localhost:5000";
                options.RequireHttpsMetadata = false;

                options.Audience = "bapi";
            });

            services.AddLocalization(options => options.ResourcesPath = "Resources");

            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new DefaultAutomapperProfile());
            });

            IMapper mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();
            services.AddScoped <Microsoft.AspNetCore.Mvc.IUrlHelper, Microsoft.AspNetCore.Mvc.Routing.UrlHelper>(
                implementationFactory =>
            {
                var actionContext = implementationFactory.GetService <IActionContextAccessor>().ActionContext;
                return(new UrlHelper(actionContext));
            }
                );
            services.AddScoped <Helpers.IUrlHelper, Helpers.UrlHelper>();
            services.AddTransient <IPropertyMappingService, PropertyMappingService>(); //transient - for stateless services
            services.AddScoped <ISecurityService, SecurityService>();
            services.AddScoped <IUserService, UserService>();
        }
Exemple #18
0
        /// <summary>
        /// configure services to be used by the asp.net runtime
        /// </summary>
        /// <param name="services">service collection</param>
        /// <returns>service provider instance (Autofac provider)</returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddApplicationInsightsTelemetry(AppSettings.Telemetry.InstrumentationKey);
                ConfigureDatabase(services);
                services.AddCors(options =>
                {
                    options.AddPolicy("CorsPolicy",
                                      cpb => cpb
                                      .AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials());
                });

                services.AddMvc(options =>
                {
                    var policy = ScopePolicy.Create(AppSettings.ServiceConfigurationOptions.RequiredScopes.ToArray());
                    options.Filters.Add(new AuthorizeFilter(policy));
                });

                services.AddApiVersioning(
                    o =>
                {
                    o.ReportApiVersions = true;
                    o.AssumeDefaultVersionWhenUnspecified = true;
                    o.DefaultApiVersion = new ApiVersion(1, 0);
                });

                services.AddSwaggerGen(c =>
                {
                    c.IncludeXmlComments("WebApi.Template.xml");
                    c.DescribeAllEnumsAsStrings();
                    c.SwaggerDoc("v1", new Info {
                        Version = "1.0.0", Title = "WebApi.Template"
                    });
                    c.CustomSchemaIds(x => x.FullName);
                    c.AddSecurityDefinition("Bearer",
                                            new ApiKeyScheme
                    {
                        In          = "header",
                        Description = "Please insert JWT with Bearer into field",
                        Name        = "Authorization",
                        Type        = "apiKey"
                    });
                });

                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddIdentityServerAuthentication(x =>
                {
                    x.ApiName              = AppSettings.ServiceConfigurationOptions.ApiName;
                    x.SupportedTokens      = SupportedTokens.Jwt;
                    x.RequireHttpsMetadata = AppSettings.ServiceConfigurationOptions.IsHttps;
                    x.Authority            = AppSettings.ServiceConfigurationOptions.Authority;
                    x.RequireHttpsMetadata = AppSettings.ServiceConfigurationOptions.IsHttps;
                    //TODO: this requires Eshopworld.Beatles.Security to be refactored
                    //x.AddJwtBearerEventsTelemetry(bb);
                });

                services.AddMvc().AddFluentValidation(fvc => fvc.RegisterValidatorsFromAssemblyContaining <NameAddressesValidator>());

                var builder = new ContainerBuilder();
                builder.Populate(services);
                builder.RegisterInstance(_bb).As <IBigBrother>().SingleInstance();
                builder.RegisterInstance(AppSettings).AsSelf().SingleInstance();

                // add additional services or modules into container here

                var container = builder.Build();
                return(new AutofacServiceProvider(container));
            }
            catch (Exception e)
            {
                _bb.Publish(e.ToBbEvent());
                throw;
            }
        }
        public virtual IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddOption <TOptions>(this.Configuration);
            services.AddOption <RedisOptions>(this.Configuration, out var redis);
            services.AddSerilog(this.Configuration, this.AppName);

            Log.Logger.Information(
                "Startup: {@node}",
                new
            {
                this.Options.ApiName,
                this.Options.ApiScope,
                ApiSecret = this.Options.ApiSecret.ToSecretString(),
                this.Options.Authority,
                this.Options.ClientId,
                ClientSecret = this.Options.ClientSecret.ToSecretString(),
                this.Options.ClockSkew,
                Redis = redis.Host,
                this.Options.Name,
            });

            services.AddDistributedRedisCache(
                options =>
            {
                options.Configuration = redis.Host;
                options.InstanceName  = this.AppName;
            });

            services.AddSerilog(this.Configuration, this.AppName);

            var mvc = services.AddMvcCore()
                      .AddCors()
                      .AddApiExplorer()
                      .AddAuthorization()
                      .AddFormatterMappings()
                      .AddJsonFormatters()
                      .AddMvcOptions(
                options =>
            {
                var policy = ScopePolicy.Create(this.Options.ApiScope);
                options.Filters.Add(new AuthorizeFilter(policy));
            })
                      .AddAuthorization(options => options.AddPolicy(this.Options.ApiScope, configure => configure.RequireAuthenticatedUser()))
                      .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            this.ConfigureMvc(mvc);

            this.CreateAuthenticationBuilder(services)
            .AddIdentityServerAuthentication(
                options =>
            {
                options.ApiName                = this.Options.ApiName;
                options.ApiSecret              = this.Options.ApiSecret;
                options.Authority              = this.Options.Authority;
                options.RequireHttpsMetadata   = false;
                options.JwtValidationClockSkew = this.Options.ClockSkew;
            });

            services.AddSwaggerDocument(
                options =>
            {
                options.DocumentName = this.AppVersion;
                options.Title        = this.AppName;

                options.DocumentProcessors.Add(
                    new SecurityDefinitionAppender(
                        IdentityServerAuthenticationDefaults.AuthenticationScheme,
                        new SwaggerSecurityScheme
                {
                    Type        = SwaggerSecuritySchemeType.ApiKey,
                    Name        = "Authorization",
                    Description = IdentityServerAuthenticationDefaults.AuthenticationScheme,
                    In          = SwaggerSecurityApiKeyLocation.Header,
                }));

                var scheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
                options.OperationProcessors.Add(new OperationSecurityScopeProcessor(scheme));

                options.OperationProcessors.Add(new UnauthorizedOperationProcessor());
            });

            return(services.BuildServiceProvider());
        }
        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>();
        }
Exemple #21
0
        /// <summary>
        /// configure services to be used by the asp.net runtime
        /// </summary>
        /// <param name="services">service collection</param>
        /// <returns>service provider instance (Autofac provider)</returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddApplicationInsightsTelemetry(_telemetrySettings.InstrumentationKey);
                services.Configure <ServiceConfigurationOptions>(_configuration.GetSection("ServiceConfigurationOptions"));

                var serviceConfigurationOptions = services.BuildServiceProvider()
                                                  .GetService <IOptions <ServiceConfigurationOptions> >();

                services.AddMvc(options =>
                {
                    var filter =
#if (DEBUG)
                        new AllowAnonymousFilter();
#else
                        var policy = ScopePolicy.Create(serviceConfigurationOptions.Value.RequiredScopes.ToArray());
                    (IFilterMetadata) new AuthorizeFilter(policy) :
#endif

                    options.Filters.Add(filter);
                });
                services.AddApiVersioning();

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

                //if not generated throw an event but it's not going to stop the app from starting
                if (!File.Exists(path))
                {
                    BigBrother.Write(new Exception("Swagger XML document has not been included in the project"));
                }
                else
                {
                    services.AddSwaggerGen(c =>
                    {
                        c.IncludeXmlComments(path);
                        c.DescribeAllEnumsAsStrings();
                        c.SwaggerDoc("v1", new OpenApiInfo {
                            Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(), Title = "ISummonNoobs"
                        });
                        c.CustomSchemaIds(x => x.FullName);
                        c.AddSecurityDefinition("Bearer",
                                                new OpenApiSecurityScheme
                        {
                            In           = ParameterLocation.Header,
                            Description  = "Please insert JWT with Bearer into field",
                            Type         = UseOpenApiV2 ? SecuritySchemeType.ApiKey : SecuritySchemeType.Http,
                            Scheme       = "bearer",
                            BearerFormat = "JWT",
                        });

                        c.AddSecurityRequirement(new OpenApiSecurityRequirement
                        {
                            {
                                new OpenApiSecurityScheme
                                {
                                    Reference = new OpenApiReference {
                                        Type = ReferenceType.SecurityScheme, Id = "Bearer"
                                    },
                                },
                                new string[0]
                            }
                        });
                    });
                }

                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddIdentityServerAuthentication(
                    x =>
                {
                    x.ApiName              = serviceConfigurationOptions.Value.ApiName;
                    x.ApiSecret            = serviceConfigurationOptions.Value.ApiSecret;
                    x.Authority            = serviceConfigurationOptions.Value.Authority;
                    x.RequireHttpsMetadata = serviceConfigurationOptions.Value.IsHttps;
                    //TODO: this requires Eshopworld.Beatles.Security to be refactored
                    //x.AddJwtBearerEventsTelemetry(bb);
                });

                var builder = new ContainerBuilder();
                builder.Populate(services);
                builder.RegisterInstance(_bb).As <IBigBrother>().SingleInstance();

                // add additional services or modules into container here

                var container = builder.Build();
                return(new AutofacServiceProvider(container));
            }
            catch (Exception e)
            {
                _bb.Publish(e.ToExceptionEvent());
                throw;
            }
        }
Exemple #22
0
        /// <summary>
        /// The framework service configuration entry point.
        ///     Do not use this to setup anything without a <see cref="IServiceCollection"/> extension method!
        /// </summary>
        /// <param name="services">The contract for a collection of service descriptors.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddApplicationInsightsTelemetry(_configuration);
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc(BullfrogVersion.LatestApi, new Info {
                        Title = "Bullfrog Api", Version = BullfrogVersion.Bullfrog
                    });
                    c.AddSecurityDefinition("Bearer",
                                            new ApiKeyScheme
                    {
                        In          = "header",
                        Description = "Please insert JWT with Bearer into field",
                        Name        = "Authorization",
                        Type        = "apiKey"
                    });
                    var filePath = Path.Combine(
                        Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? throw new InvalidOperationException("Wrong check for the swagger XML file! 'Assembly.GetExecutingAssembly().Location' came back null!"),
                        "Bullfrog.Api.xml");

                    if (File.Exists(filePath))
                    {
                        c.IncludeXmlComments(filePath);
                    }
                    else
                    {
                        if (Debugger.IsAttached)
                        {
                            // Couldn't find the XML file! check that XML comments are being built and that the file name checks
                            Debugger.Break();
                        }
                    }
                });

                services.AddAuthorization(options =>
                {
                    options.AddPolicy("AssertScope", policy =>
                                      policy.RequireClaim("scope", "esw.bullfrog.api.all"));
                });

                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddIdentityServerAuthentication(x =>
                {
                    x.ApiName   = _configuration["STSConfig:ApiName"];
                    x.Authority = _configuration["STSConfig:Authority"];
                });

                services.AddMvc(options =>
                {
                    var policy = ScopePolicy.Create("esw.bullfrog.api.all");
                    options.Filters.Add(new AuthorizeFilter(policy));
                }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            }
            catch (Exception e)
            {
                _bb.Publish(e.ToExceptionEvent());
                _bb.Flush();
                throw;
            }
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(Configuration["SECRETS_DIR"]))
            .SetApplicationName(Configuration["Properties:ApplicationName"]);

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration["IdApiConnectionStrings:IdentityDB"], x => x.MigrationsAssembly("IdentityDataCommon")));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddRoleManager <RoleManager <IdentityRole> >()
            .AddSignInManager <SignInManager <ApplicationUser> >()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <IdentityOptions>(options =>
            {
                // Password settings.
                options.Password.RequireDigit           = true;
                options.Password.RequireLowercase       = true;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase       = true;
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 1;

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers      = true;

                // User settings.
                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._+";
                options.User.RequireUniqueEmail = false;
            });

            services.Configure <IISServerOptions>(options => { options.AutomaticAuthentication = false; });

            services.AddCors(options =>
            {
                options.AddPolicy("default", policy =>
                {
                    policy.WithOrigins(Configuration["AppURLS:IdManagementBaseUrl"], Configuration["AppURLS:IS4BaseUrl"])
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            services.AddControllers()
            .ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressModelStateInvalidFilter          = true;
                options.SuppressInferBindingSourcesForParameters = true;

                options.InvalidModelStateResponseFactory = context =>
                {
                    var result = new BadRequestObjectResult(context.ModelState);
                    result.ContentTypes.Add(MediaTypeNames.Application.Json);
                    return(result);
                };
            });

            services.AddMvcCore(options =>
            {
                //lock down this Api to only allow access tokens with IdApi scope
                var policy = ScopePolicy.Create("IdApi");
                options.Filters.Add(new AuthorizeFilter(policy));
                options.Filters.Add(typeof(ApiValidationFilterAttribute));
            })
            //https://stackoverflow.com/questions/55666826/where-did-imvcbuilder-addjsonoptions-go-in-net-core-3-0
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
                options.JsonSerializerOptions.DictionaryKeyPolicy  = null;
            })
            .AddAuthorization(options =>
            {
                options.AddPolicy("ApiScope", policy =>
                {
                    policy.RequireScope("IdApi");
                    policy.RequireAuthenticatedUser();
                    policy.RequireClaim("scope", "IdApi");
                });
            });

            services.AddLogging();
            services.AddDistributedMemoryCache();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddOAuth2Introspection("introspection", options =>
            {
                options.Authority    = Configuration["AppURLS:IS4BaseUrl"];
                options.ClientId     = Configuration["AppIds:IdManagementId"];
                options.ClientSecret = Configuration["AppSecrets:IdManagementId"];
            })
            .AddIdentityServerAuthentication("IdentityServerAccessToken", options =>
            {
                options.Authority = Configuration["AppURLS:IS4BaseUrl"];
                options.ApiName   = Configuration["ApplicationIds:IdApiId"];
                options.ApiSecret = Configuration["ApplicationSecrets:IdApiSecret"];

                //Using Reference Tokens - lessons calls to IS4 to validate tokens
                options.EnableCaching   = true; //REQUIRES: services.AddDistributedMemoryCache();
                options.CacheDuration   = TimeSpan.FromMinutes(2);
                options.SupportedTokens = SupportedTokens.Both;
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "IdApi", Version = "v1"
                });
            });
        }
Exemple #24
0
 public static void BaseConfigureServices(IServiceCollection services, BaseConfigureServiceModel baseConfigure)
 {
     #region 配置MVC
     services
     .AddMvc(options =>
     {
         AuthorizationPolicy policy = ScopePolicy.Create(ApplicationConfig.IdentityServer.Scope);
         options.Filters.Add(new AuthorizeFilter(policy));
         options.Filters.Add(typeof(ExceptionProcessFilter));
     })
     .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
     .AddJsonOptions(options =>
     {
         options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
         options.SerializerSettings.ContractResolver      = new DefaultContractResolver();
     });
     #endregion
     #region 配置Authentication
     services.AddAuthentication("Bearer")
     .AddIdentityServerAuthentication(options =>
     {
         options.Authority            = ApplicationConfig.IdentityServer.Url;
         options.RequireHttpsMetadata = false;
         options.ApiName       = ApplicationConfig.IdentityServer.Scope;
         options.ApiSecret     = ApplicationConfig.IdentityServer.Secret;
         options.EnableCaching = true;
         options.CacheDuration = TimeSpan.FromMinutes(10);
     });
     #endregion
     #region 帮助文档
     /*Swashbuckle.AspNetCore*/
     services.AddSwaggerGen(m =>
     {
         m.SwaggerDoc(baseConfigure.AppName, new Info
         {
             Version        = "0.1",
             Title          = baseConfigure.AppName,
             Description    = "提供WebAPI接口",
             TermsOfService = "None",
             Contact        = new Contact {
                 Name = "Materal", Email = "*****@*****.**", Url = ""
             }
         });
         m.AddSecurityDefinition("Bearer", new ApiKeyScheme
         {
             Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
             Name        = "Authorization",
             In          = "header",
             Type        = "apiKey"
         });
         m.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
         {
             { "Bearer", Enumerable.Empty <string>() }
         });
         foreach (string path in baseConfigure.SwaggerHelperXmlPathArray)
         {
             m.IncludeXmlComments(path);
         }
     });
     #endregion
     #region 跨域
     services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                   .AllowAnyMethod()
                                                   .AllowAnyHeader()));
     #endregion
 }