public void ConfigureServices(IServiceCollection services) { services.AddAuthorization(options => { options.AddPolicy(PolicyNames.AdministratorsOnly, policy => policy.RequireRole("Administrator")); options.AddPolicy(PolicyNames.CanEditAlbum, policy => { policy.Requirements.Add(new AlbumOwnerRequirement()); policy.RequireRole("Administrator"); } ); }); services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); services.AddSingleton<IUserRepository, UserRepository>(); services.AddSingleton<IAlbumRepository, AlbumRepository>(); services.AddSingleton<IAuthorizationHandler, AlbumOwnerAuthorizationHandler>(); }
// This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddAuthorization(); services.AddOptions(); services.Configure<ConnectionOptions>(Configuration); services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); services.AddCors(); services.AddSwaggerGen(); services.AddRepositoryRegistrations(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var defaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() //.RequireRole("role-i-am-in") .Build(); // Add framework services. services.AddMvc(setup => { setup.Filters.Add(new AuthorizeFilter(defaultPolicy)); }); //services.AddAuthorization(options => //{ // options.AddPolicy("Testing", policy => // { // policy.RequireRole("role-i-am-in"); // }); //}); services.AddScoped<Models.SelectLists>(); var connection = Configuration["Data:DefaultConnection:ConnectionString"]; var path = Environment.WebRootPath; var dir = Directory.GetParent(path).Parent.FullName; connection = string.Format(connection, dir); services.AddEntityFramework() .AddSqlServer() .AddDbContext<SCRUDContext>(options => options.UseSqlServer(connection)); }
public void ConfigureServices(IServiceCollection services) { // only allow authenticated users var defaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); services.AddMvc(setup => { setup.Filters.Add(new AuthorizeFilter(defaultPolicy)); }); services.AddAuthorization(options => { // some examples options.AddPolicy("SalesOnly", policy => { policy.RequireClaim("department", "sales"); }); options.AddPolicy("SalesSenior", policy => { policy.RequireClaim("department", "sales"); policy.RequireClaim("status", "senior"); }); options.AddPolicy("DevInterns", policy => { policy.RequireClaim("department", "development"); policy.RequireClaim("status", "intern"); }); options.AddPolicy("Over18", policy => { policy.RequireDelegate((context, requirement) => { var age = context.User.FindFirst("age")?.Value ?? "0"; if (int.Parse(age) >= 18) { context.Succeed(requirement); } else { context.Fail(); } }); }); // custom policy options.AddPolicy("CxO", policy => { policy.RequireJobLevel(JobLevel.CxO); }); }); // register resource authorization handlers services.AddTransient<IAuthorizationHandler, CustomerAuthorizationHandler>(); services.AddTransient<IAuthorizationHandler, ProductAuthorizationHandler>(); // register data access services services.AddTransient<IPermissionService, PermissionService>(); services.AddTransient<IOrganizationService, OrganizationService>(); }
// TODO: Add unit tests public static AuthorizationPolicy Combine([NotNull] IEnumerable<AuthorizationPolicy> policies) { var builder = new AuthorizationPolicyBuilder(); foreach (var policy in policies) { builder.Combine(policy); } return builder.Build(); }
// 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 http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddAuthorization(); services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ConfigureSecurity(services); var useGlimpse = Configuration.Get<bool>("Glimpse:Enabled"); if (useGlimpse) { services.AddGlimpse(); } var useFeatureFolders = Configuration.Get<bool>("FeatureFolders:Enabled"); services.Configure<RazorViewEngineOptions>(o => { o.ViewLocationExpanders.Add(new FeatureFolderLocationRemapper()); }); // Add framework services. var connectionString = Configuration["Data:DefaultConnection:ConnectionString"]; services.AddEntityFramework() .AddSqlServer() .AddDbContext<DomainContext>(options => { options.UseSqlServer(connectionString); }) .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString)); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // only allow authenticated users //http://leastprivilege.com/2015/10/12/the-state-of-security-in-asp-net-5-and-mvc-6-authorization/ var defaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); services.AddCors(); services.AddSingleton<LogFilter>(); //services.AddCors(); services.AddMvc().AddMvcOptions( options => { options.ModelBinders.Insert(0, new TrimmingSimpleTypeModelBinder()); options.Filters.Add(new AuthorizeFilter(defaultPolicy)); options.ModelMetadataDetailsProviders.Add(new HumanizerMetadataProvider()); }).AddFluentValidation(); // Add application services. services.AddTransient<IValidatorFactory, MvcValidatorFactory>(); services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); }
public static AuthorizationPolicy Combine(IEnumerable<AuthorizationPolicy> policies) { if (policies == null) { throw new ArgumentNullException(nameof(policies)); } var builder = new AuthorizationPolicyBuilder(); foreach (var policy in policies) { builder.Combine(policy); } return builder.Build(); }
public static AuthorizationPolicy Combine(AuthorizationOptions options, IEnumerable<IAuthorizeData> attributes) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (attributes == null) { throw new ArgumentNullException(nameof(attributes)); } var policyBuilder = new AuthorizationPolicyBuilder(); var any = false; foreach (var authorizeAttribute in attributes.OfType<AuthorizeAttribute>()) { any = true; var useDefaultPolicy = true; if (!string.IsNullOrWhiteSpace(authorizeAttribute.Policy)) { var policy = options.GetPolicy(authorizeAttribute.Policy); if (policy == null) { throw new InvalidOperationException(Resources.FormatException_AuthorizationPolicyNotFound(authorizeAttribute.Policy)); } policyBuilder.Combine(policy); useDefaultPolicy = false; } var rolesSplit = authorizeAttribute.Roles?.Split(','); if (rolesSplit != null && rolesSplit.Any()) { policyBuilder.RequireRole(rolesSplit); useDefaultPolicy = false; } var authTypesSplit = authorizeAttribute.ActiveAuthenticationSchemes?.Split(','); if (authTypesSplit != null && authTypesSplit.Any()) { foreach (var authType in authTypesSplit) { policyBuilder.AuthenticationSchemes.Add(authType); } } if (useDefaultPolicy) { policyBuilder.Combine(options.DefaultPolicy); } } return any ? policyBuilder.Build() : null; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // only allow authenticated users var defaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); services.AddMvc(setup => { setup.Filters.Add(new AuthorizeFilter(defaultPolicy)); }); services.AddAuthorization(options => { // inline policies options.AddPolicy("SalesOnly", policy => { policy.RequireClaim("department", "sales"); }); options.AddPolicy("SalesSenior", policy => { policy.RequireClaim("department", "sales"); policy.RequireClaim("status", "senior"); }); }); // Add Entity Framework services to the services container. services.AddEntityFramework() .AddSqlServer() .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); // Add Identity services to the services container. services.AddIdentity<ApplicationUser, ApplicationRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // Add MVC services to the services container. services.AddMvc(); // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers. // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json. // services.AddWebApiConventions(); // Register application services. services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); }
// 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 http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddAuthorization(options => { options.AddPolicy("AdministratorOnly", policy => policy.RequireRole("Administrator")); options.AddPolicy("EmployeeId", policy => policy.RequireClaim("EmployeeId", "123", "456")); }); services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add localization with Resources file. OKL services.AddLocalization(options => options.ResourcesPath = "Resources"); // Add framework services. services.AddEntityFramework() .AddSqlServer() .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])) .AddDbContext<IdentityDbContext>(opts => opts.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); // Configure identity options and password requirements. OKL services.AddIdentity<ApplicationUser, IdentityRole>(o => { o.Password.RequireDigit = false; o.Password.RequireLowercase = false; o.Password.RequireUppercase = false; o.Password.RequireNonLetterOrDigit = false; ; o.Password.RequiredLength = 6; }) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // Add authorization policy: only allow authenticated users. OKL var defaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); // Add MVC and enforce authorization policy from above. OKL services.AddMvc(setup => { setup.Filters.Add(new Microsoft.AspNet.Mvc.Filters.AuthorizeFilter(defaultPolicy)); }) // Add localization. OKL .AddViewLocalization() .AddDataAnnotationsLocalization(); ; ; // Add application services. services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); ; }
// 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 http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddAuthorization(options => { options.AddPolicy("AdministratorOnly", policy => policy.RequireRole("Administrator")); options.AddPolicy("EmployeeId", policy => policy.RequireClaim("EmployeeId", "123", "456")); options.AddPolicy("Over21Only", policy => policy.Requirements.Add(new MinimumAgeRequirement(21))); options.AddPolicy("BuildingEntry", policy => policy.Requirements.Add(new OfficeEntryRequirement())); }); services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); services.AddSingleton<IAuthorizationHandler, HasBadgeHandler>(); services.AddSingleton<IAuthorizationHandler, HasTemporaryBadgeHandler>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddEntityFramework() .AddSqlServer() .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])) .AddDbContext<PuzzleAdvDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddMvc(); // Add application services. services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); services.Configure<AuthMessageSenderOptions>(Configuration); // only allow authenticated users var defaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); services.AddMvc(setup => { setup.Filters.Add(new AuthorizeFilter(defaultPolicy)); }); services.AddAuthorization(options => { options.AddPolicy("AdminOnly", policy => { policy.RequireRole("Admin"); }); }); services.AddScoped<IPuzzleRepository, PuzzleRepository>(); services.AddScoped<IShopRepository, ShopRepository>(); }
// This method gets called by a runtime. // Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { var defaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme) .Build(); services.AddLogging(); IMvcBuilder mvcBuilder = services.AddMvc(options => { options.Filters.Add(new AuthorizeFilter(defaultPolicy)); }); string mongoConnection = Configuration.GetSection("Data:DefaultConnection:Mongo").Value; /** * Register the things */ services.AddSingleton(typeof(IDocumentProvider), x => { return new MongoDBDocumentProvider(mongoConnection); }); services.AddSingleton<SchoolDataContext>(); services.AddAuthentication(); services.AddSession(); services.AddCaching(); services.AddTransient(typeof(User)); services.AddTransient(typeof(IEncryption), typeof(Encryption)); services.AddTransient(typeof(IModelCreator), typeof(ModelCreator)); /** * Build service provider */ IServiceProvider provider = services.BuildServiceProvider(); /** * Setup serializer */ mvcBuilder.AddJsonOptions(x => { x.SerializerSettings.ContractResolver = new DIContractResolver(provider.GetService<IModelCreator>()); }); services.AddAuthorization(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(x => x.AddPolicy("allowall", new CorsPolicy { Origins = { "http://localhost:8001" }, Headers = { "*" }, Methods = { "*" }, SupportsCredentials = true, })); // Add framework services. services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); }
public void ConfigureServices(IServiceCollection services) { // only allow authenticated users var defaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); services.AddMvc(setup => { setup.Filters.Add(new AuthorizeFilter(defaultPolicy)); }); services.AddAuthorization(options => { // inline policies options.AddPolicy("SalesOnly", policy => { policy.RequireClaim("department", "sales"); }); options.AddPolicy("SalesSenior", policy => { policy.RequireClaim("department", "sales"); policy.RequireClaim("status", "senior"); }); // custom policy options.AddPolicy("DevInterns", policy => { policy.AddRequirements(new StatusRequirement("development", "intern")); // ..or using extension method //policy.RequireStatus("development", "intern"); }); }); // register resource authorization handlers services.AddTransient<IAuthorizationHandler, CustomerAuthorizationHandler>(); services.AddTransient<IAuthorizationHandler, ProductAuthorizationHandler>(); // register permission store services.AddTransient<IPermissionService, TestPermissionService>(); }
public static AuthorizationPolicy Combine([NotNull] AuthorizationOptions options, [NotNull] IEnumerable<AuthorizeAttribute> attributes) { var policyBuilder = new AuthorizationPolicyBuilder(); bool any = false; foreach (var authorizeAttribute in attributes.OfType<AuthorizeAttribute>()) { any = true; var requireAnyAuthenticated = true; if (!string.IsNullOrWhiteSpace(authorizeAttribute.Policy)) { var policy = options.GetPolicy(authorizeAttribute.Policy); if (policy == null) { throw new InvalidOperationException(Resources.FormatException_AuthorizationPolicyNotFound(authorizeAttribute.Policy)); } policyBuilder.Combine(policy); requireAnyAuthenticated = false; } var rolesSplit = authorizeAttribute.Roles?.Split(','); if (rolesSplit != null && rolesSplit.Any()) { policyBuilder.RequireRole(rolesSplit); requireAnyAuthenticated = false; } string[] authTypesSplit = authorizeAttribute.ActiveAuthenticationSchemes?.Split(','); if (authTypesSplit != null && authTypesSplit.Any()) { foreach (var authType in authTypesSplit) { policyBuilder.ActiveAuthenticationSchemes.Add(authType); } } if (requireAnyAuthenticated) { policyBuilder.RequireAuthenticatedUser(); } } return any ? policyBuilder.Build() : null; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(); services.Configure<Auth0Settings>(Configuration.GetSection("Auth0")); // Add framework services. services.AddMvc(); var defaultPolicy = new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build(); // Enable the use of an [Authorize("Bearer")] attribute on methods and // classes to protect. services.AddAuthorization(auth => { auth.AddPolicy("Bearer", defaultPolicy); }); services.AddCors(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddEntityFramework() .AddSqlServer() .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); var defaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); //services.AddIdentity<ApplicationUser, IdentityRole>() // .AddEntityFrameworkStores<ApplicationDbContext>() // .AddDefaultTokenProviders(); // services.AddMvc(setup => // { // setup.Filters.Add(new AuthorizeFilter(defaultPolicy)); // }); services.AddMvc(); services.AddAuthorization(options => { // inline policies options.AddPolicy("SalesOnly", policy => { policy.RequireClaim("department", "sales"); }); options.AddPolicy("SalesSenior", policy => { policy.RequireClaim("department", "sales"); policy.RequireClaim("status", "senior"); }); }); // Add application services. //services.AddTransient<IEmailSender, AuthMessageSender>(); //services.AddTransient<ISmsSender, AuthMessageSender>(); }
public void ConfigureServices(IServiceCollection services) { // only allow authenticated users var defaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); services.AddMvc(setup => { setup.Filters.Add(new AuthorizeFilter(defaultPolicy)); }); services.ConfigureAuthorization(options => { // inline policies options.AddPolicy("SalesOnly", policy => { policy.RequireClaim("department", "sales"); }); options.AddPolicy("SalesSenior", policy => { policy.RequireClaim("department", "sales"); policy.RequireClaim("status", "senior"); }); // custom policy options.AddPolicy("DevInterns", policy => { policy.AddRequirements(new StatusRequirement("development", "intern")); // ..or using extension method //policy.RequireStatus("development", "intern"); }); }); }
public void ConfigureServices(IServiceCollection services, IConfigurationRoot configuration) { services.AddEntityFramework() .AddSqlServer() .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(configuration["Data:DefaultConnection:ConnectionString"])); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); var defaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); // Add framework services. services .AddMvc(setup => { setup.Filters.Add(new AuthorizeFilter(defaultPolicy)); }) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); // Add CORS support services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()); }); services.AddScoped<IUsersRepository, AspNetIdentityUsersRepository>(); services.AddScoped<IUserClaimsRepository, AspNetIdentityUserClaimsRepository>(); }
public void AddPolicy([NotNull] string name, [NotNull] Action<AuthorizationPolicyBuilder> configurePolicy) { var policyBuilder = new AuthorizationPolicyBuilder(); configurePolicy(policyBuilder); PolicyMap[name] = policyBuilder.Build(); }
// This method gets called by the runtime. public void ConfigureServices(IServiceCollection services) { // Add MVC services to the services container. services.AddMvc(); services.ConfigureAuthorization(authzOptions => { var defaultPolicy = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme) .RequireClaim(System.Security.Claims.ClaimTypes.NameIdentifier) .Build(); authzOptions.AddPolicy(Constants.WebsiteReadPolicy, policy => { policy.Combine(defaultPolicy); policy.RequireClaim("scope", "read"); }); authzOptions.AddPolicy(Constants.WebsiteWritePolicy, policy => { policy.Combine(defaultPolicy); policy.RequireClaim("scope", "write"); }); }); }