本文整理汇总了C#中IServiceCollection.AddAuthorization方法的典型用法代码示例。如果您正苦于以下问题:C# IServiceCollection.AddAuthorization方法的具体用法?C# IServiceCollection.AddAuthorization怎么用?C# IServiceCollection.AddAuthorization使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IServiceCollection
的用法示例。
在下文中一共展示了IServiceCollection.AddAuthorization方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//load key from file
RSAParameters keyParams = SecurityRSAUtils.GetKeyParameters(@"C:\_Projects\auth.spear.roimantra.com\src\auth.spear.roimantra.com\SecurityKey\jwt_private_security_key.txt");
_securityKey = new RsaSecurityKey(keyParams);
_tokenOptions = new SecurityTokenAuthOptions()
{
Audience = TokenAudience,
Issuer = TokenIssuer,
SigningCredentials = new SigningCredentials(_securityKey, SecurityAlgorithms.RsaSha256Signature)
};
// Save the token options into an instance so they're accessible to the
// controller.
services.AddInstance<SecurityTokenAuthOptions>(_tokenOptions);
// Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect.
services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});
services.AddMvc();
}
示例2: ConfigureServices
// This method gets called by a runtime.
// Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.ConfigureCors(options =>
{
options.AddPolicy("AllowSpecificOrigins",
builder => builder.WithOrigins("http://localhost:15831")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.Build());
});
//services.AddAuthorization(options =>
//{
// options.AddPolicy("GetTokenClaims",
// policy => policy.Requirements.Add(new Karama.Resources.Aspnet5.Controllers.GetTokenClaimsRequirement()));
//});
services.AddAuthorization(options =>
{
options.AddPolicy("GetTokenClaims",
policy => policy.RequireClaim("role", "gettokenclaims"));
});
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();
}
示例3: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var s = services.FirstOrDefault(x => x.ServiceType == typeof(IHostingEnvironment));
var env = s.ImplementationInstance as IHostingEnvironment;
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite([email protected]"Data Source={env.ContentRootPath}/j64.AlarmServer.db"));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthorization(options =>
{
options.AddPolicy("ArmDisarm", policy => policy.RequireClaim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "ArmDisarm"));
});
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
// Add a single instance of the alarm system
var alarmSystem = Repository.AlarmSystemRepository.Get();
alarmSystem.ZoneChange += SmartThingsRepository.AlarmSystem_ZoneChange;
alarmSystem.PartitionChange += SmartThingsRepository.AlarmSystem_PartitionChange;
alarmSystem.StartSession();
services.AddSingleton<AlarmSystem>(alarmSystem);
}
示例4: ConfigureServices
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>();
}
示例5: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add Stormpath services
var stormpathConfiguration = new StormpathConfiguration()
{
Web = new WebConfiguration()
{
ServerUri = "http://localhost:8080",
Login = new WebLoginRouteConfiguration()
//{
// View = "~/Views/Stormpath/MyLogin.cshtml"
//}
}
};
services.AddStormpath(stormpathConfiguration);
// Configure authorization policies here, which can include Stormpath requirements.
services.AddAuthorization(opt =>
{
opt.AddPolicy("CustomDataIT", policy => policy.AddRequirements(new StormpathCustomDataRequirement("testing", "rocks!")));
opt.AddPolicy("AdminITGroup", policy => policy.AddRequirements(new StormpathGroupsRequirement("adminIT")));
});
// Add framework services.
services.AddMvc();
}
示例6: ConfigureServices
// 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.AddEntityFramework()
.AddSqlServer()
.AddDbContext<MyHealthContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddScoped<ApplicationUsersRepository>();
services.AddScoped<ApplicationUserValidators>();
services.AddScoped<PatientsRepository>();
services.AddScoped<ClinicAppointmentsRepository>();
services.AddScoped<ReportsRepository>();
services.AddScoped<HomeAppointmentRepository>();
services.AddScoped<MedicinesRepository>();
services.AddScoped<TipsRepository>();
services.AddScoped<DoctorsRepository>();
services.AddScoped<TenantsRepository>();
services.AddScoped<MyHealthDataInitializer>();
services.AddMvc();
services.AddAuthorization(Policies.Configuration);
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<MyHealthContext>()
.AddDefaultTokenProviders();
}
示例7: ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication();
// OPTIONAL: Use a custom authorization handler to implement resource-based
// authorization in the application.
// services.AddTransient<IAuthorizationHandler,AdminUserHandler>();
// The authorization for the application is defined in a number of policies.
// Each policy defines what the user has to comply to in order to get access.
services.AddAuthorization(authorization => {
authorization.AddPolicy("Anonymous", policy => policy.RequireDelegate((context,requirement) => {
// When none of the identities are authenticated the user is anonymous.
// So the requirement was succesful.
if(context.User.Identities.All(identity => !identity.IsAuthenticated)) {
context.Succeed(requirement);
} else {
context.Fail();
}
}));
authorization.AddPolicy("Authenticated", policy => policy.RequireAuthenticatedUser());
});
services.AddMvc();
}
示例8: ConfigureServices
// 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();
}
示例9: ConfigureServices
// 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()
.AddSqlite()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders() ;
services.AddAuthorization(options =>
{
options.AddPolicy("ArmDisarm", policy => policy.RequireClaim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "ArmDisarm"));
});
services.AddMvc();
// Setup the alarm system
AlarmSystem alarmSystem = AlarmSystemRepository.Get();
alarmSystem.ZoneChange += SmartThingsRepository.AlarmSystem_ZoneChange;
alarmSystem.PartitionChange += SmartThingsRepository.AlarmSystem_PartitionChange;
alarmSystem.StartSession();
// Add the alarm system as a service available to the controllers
services.AddInstance<AlarmSystem>(alarmSystem);
services.AddTransient<SampleDataInitializer>();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
示例10: ConfigureServices
// 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)
{
// Add Entity Framework services to the services container.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<PhotoGalleryContext>(options =>
options.UseSqlServer(Configuration["Data:PhotoGalleryConnection:ConnectionString"]));
// Repositories
services.AddScoped<IPhotoRepository, PhotoRepository>();
services.AddScoped<IAlbumRepository, AlbumRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IUserRoleRepository, UserRoleRepository>();
services.AddScoped<IRoleRepository, RoleRepository>();
services.AddScoped<ILoggingRepository, LoggingRepository>();
// Services
services.AddScoped<IMembershipService, MembershipService>();
services.AddScoped<IEncryptionService, EncryptionService>();
services.AddAuthentication();
// Policies
services.AddAuthorization(options =>
{
// inline policies
options.AddPolicy("AdminOnly", policy =>
{
policy.RequireClaim(ClaimTypes.Role, "Admin");
});
});
// Add MVC services to the services container.
services.AddMvc();
}
示例11: AddAuthorizationServices
// Internal for testing.
internal static void AddAuthorizationServices(IServiceCollection services)
{
services.AddAuthorization();
services.TryAddEnumerable(
ServiceDescriptor.Transient<IApplicationModelProvider, AuthorizationApplicationModelProvider>());
}
示例12: ConfigureServices
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>();
}
示例13: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var useInMemoryStore = !_Platform.IsRunningOnWindows || _Platform.IsRunningOnMono || _Platform.IsRunningOnNanoServer;
services.ConfigureDataContext(Configuration, useInMemoryStore);
// Register dependencies
services.ConfigureDependencies();
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<MyHealthContext>()
.AddDefaultTokenProviders();
services.AddApplicationInsightsTelemetry(Configuration);
// Add MVC services to the services container.
services.AddMvc();
services.AddCaching();
services.AddSession();
services.AddAuthorization(Policies.Configuration);
}
示例14: ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("RolesAreOldSchoolDontDoThis", policy => policy.RequireRole("Administrator"));
options.AddPolicy("RequireBobTheBuilder", policy => policy.RequireClaim("CanWeFixIt"));
options.AddPolicy("Over18", policy => policy.Requirements.Add(new Authorization.Over18Requirement()));
options.AddPolicy("Over21", policy => policy.Requirements.Add(new Authorization.MinimumAgeRequirement(21)));
options.AddPolicy("TacoTuesday", policy => policy.Requirements.Add(new Authorization.DayRequirement(DayOfWeek.Tuesday)));
options.AddPolicy("TequillaTacoTuesday", policy =>
{
policy.Requirements.Add(new Authorization.DayRequirement(DayOfWeek.Thursday));
policy.Requirements.Add(new Authorization.MinimumAgeRequirement(21));
});
options.AddPolicy("Documents", policy => policy.RequireClaim("Documents"));
options.AddPolicy("WebApi", policy =>
{
policy.AuthenticationSchemes.Add("Bearer");
policy.RequireAuthenticatedUser();
});
options.AddPolicy("CookieBearer", policy =>
{
policy.AuthenticationSchemes.Add("Bearer");
policy.AuthenticationSchemes.Add("Cookie");
policy.RequireAuthenticatedUser();
});
options.AddPolicy("NoGingers", policy =>
{
policy.Requirements.Add(new Authorization.NoGingersRequirement());
});
options.AddPolicy("CanEnterContosoBuilding", policy =>
{
policy.Requirements.Add(new Authorization.EnterBuildingRequirement());
});
});
services.AddSingleton<IAuthorizationHandler, Authorization.DocumentAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, Authorization.BaldAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, Authorization.NoGingersAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, Authorization.BuildingEntryAsEmployeeHandler>();
services.AddSingleton<IAuthorizationHandler, Authorization.BuildingEntryAsVisitor>();
services.AddSingleton<IEmployeeRepository, EmployeeRepository>();
}
示例15: ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication();
services.AddAuthorization(options =>
{
options.AddPolicy("Authenticated", p => p.RequireAuthenticatedUser());
});
}