本文整理汇总了C#中IServiceCollection.ConfigureAuthorization方法的典型用法代码示例。如果您正苦于以下问题:C# IServiceCollection.ConfigureAuthorization方法的具体用法?C# IServiceCollection.ConfigureAuthorization怎么用?C# IServiceCollection.ConfigureAuthorization使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IServiceCollection
的用法示例。
在下文中一共展示了IServiceCollection.ConfigureAuthorization方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ConfigureServices
// This method gets called by a runtime.C:\Projects\toprak\ToprakWeb\gruntfile.js
// Use this method to add services to the container
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(this.config);
services.AddAuthentication(options => options.SignInScheme = "ToprakWeb");
services.ConfigureAuthorization(
options =>
{
options.AddPolicy("MustBeAdmin", policy => policy.Requirements.Add(new RoleRequirement("Admin")));
options.AddPolicy("MustBeUser", policy => policy.Requirements.Add(new RoleRequirement("User")));
});
services.AddMvc();
var builder = new ContainerBuilder();
builder.RegisterModule(new AutofacModule(config));
builder.Populate(services);
var container = builder.Build();
return container.Resolve<IServiceProvider>();
}
示例2: ConfigureServices
// Set up application services
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.ConfigureAuthorization(options =>
{
// This policy cannot succeed since the claim is never added
options.AddPolicy("Impossible", policy =>
{
policy.ActiveAuthenticationSchemes.Add("Interactive");
policy.RequireClaim("Never");
});
options.AddPolicy("Api", policy =>
{
policy.ActiveAuthenticationSchemes.Add("Api");
policy.RequireClaim(ClaimTypes.NameIdentifier);
});
options.AddPolicy("Api-Manager", policy =>
{
policy.ActiveAuthenticationSchemes.Add("Api");
policy.Requirements.Add(Operations.Edit);
});
options.AddPolicy("Interactive", policy =>
{
policy.ActiveAuthenticationSchemes.Add("Interactive");
policy.RequireClaim(ClaimTypes.NameIdentifier)
.RequireClaim("Permission", "CanViewPage");
});
});
services.AddSingleton<RandomNumberFilter>();
services.AddSingleton<RandomNumberService>();
services.AddTransient<IAuthorizationHandler, ManagerHandler>();
services.Configure<BasicOptions>(o => o.AuthenticationScheme = "Api", "Api");
services.Configure<BasicOptions>(o => o.AuthenticationScheme = "Interactive", "Interactive");
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new GlobalExceptionFilter());
options.Filters.Add(new GlobalActionFilter());
options.Filters.Add(new GlobalResultFilter());
options.Filters.Add(new GlobalAuthorizationFilter());
options.Filters.Add(new TracingResourceFilter("Global Resource Filter"));
});
}
示例3: 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.
string connectionString = Configuration["Data:DefaultConnection:ConnectionString"];
services
.AddDbContext<SecurityDbContext>(options => options.UseSqlServer(connectionString))
.AddDbContext<DomainContext>(options => options.UseSqlServer(connectionString));
services.ConfigureAuthorization();
services.AddMvc();
services.AddScoped<ValidateMimeMultipartContentFilter>();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddTransient<IRepository<Project>, ProjectRepository>();
services.AddTransient<IRepository<Applicant>, ApplicantRepository>();
services.AddTransient<IRepository<Domain.Core.File>, FileRepository>();
}
示例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.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");
});
});
}
示例5: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookieAuthenticationOptions>(options =>
{
options.AutomaticAuthentication = true;
});
services.Configure<OpenIdConnectAuthenticationOptions>(options =>
{
options.AutomaticAuthentication = true;
options.ClientId = Configuration["Authentication:AzureAd:ClientId"];
options.Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"];
options.PostLogoutRedirectUri = Configuration["Authentication:AzureAd:PostLogoutRedirectUri"];
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
services.ConfigureAuthorization(options =>
{
options.AddPolicy("Admin", policyBuilder =>
{
policyBuilder.RequireClaim(
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
Configuration["Authorization:AdminUsers"].Split(',')
);
});
});
// Add MVC services to the services container.
services.AddMvc();
var context = new TableCacheContext(Configuration["Authentication:AzureStorageAccount:StorageConnectionString"], Configuration["Authentication:AzureStorageAccount:version"]);
services.AddInstance<ITableContext>(context);
}
示例6: ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.ConfigureAuthorization(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.ActiveAuthenticationSchemes.Add("Bearer");
policy.RequireAuthenticatedUser();
});
options.AddPolicy("CookieBearer", policy =>
{
policy.ActiveAuthenticationSchemes.Add("Bearer");
policy.ActiveAuthenticationSchemes.Add("Cookie");
policy.RequireAuthenticatedUser();
});
});
services.AddInstance<IAuthorizationHandler>(new Authorization.DocumentAuthorizationHandler());
}
示例7: ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
//If this type is present - we're on mono
var runningOnMono = Type.GetType("Mono.Runtime") != null;
var sqlConnectionString = Configuration["Data:DefaultConnection:ConnectionString"];
var useInMemoryDatabase = string.IsNullOrWhiteSpace(sqlConnectionString);
// Add EF services to the services container
if (useInMemoryDatabase || runningOnMono)
{
services.AddEntityFramework()
.AddInMemoryDatabase()
.AddDbContext<PartsUnlimitedContext>(options =>
{
options.UseInMemoryDatabase();
});
}
else
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<PartsUnlimitedContext>(options =>
{
options.UseSqlServer(sqlConnectionString);
});
}
// Add Identity services to the services container
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<PartsUnlimitedContext>()
.AddDefaultTokenProviders();
// Configure admin policies
services.ConfigureAuthorization(auth =>
{
auth.AddPolicy(AdminConstants.Role,
new AuthorizationPolicyBuilder()
.RequireClaim(AdminConstants.ManageStore.Name, AdminConstants.ManageStore.Allowed)
.Build());
});
// Add implementations
services.AddSingleton<IMemoryCache, MemoryCache>();
services.AddScoped<IOrdersQuery, OrdersQuery>();
services.AddScoped<IRaincheckQuery, RaincheckQuery>();
services.AddSingleton<ITelemetryProvider, EmptyTelemetryProvider>();
services.AddScoped<IProductSearch, StringContainsProductSearch>();
SetupRecommendationService(services);
services.AddScoped<IWebsiteOptions>(p =>
{
var telemetry = p.GetRequiredService<ITelemetryProvider>();
return new ConfigurationWebsiteOptions(Configuration.GetSection("WebsiteOptions"), telemetry);
});
services.AddScoped<IApplicationInsightsSettings>(p =>
{
return new ConfigurationApplicationInsightsSettings(Configuration.GetSection("Keys:ApplicationInsights"));
});
// Associate IPartsUnlimitedContext with context
services.AddTransient<IPartsUnlimitedContext>(s => s.GetService<PartsUnlimitedContext>());
// We need access to these settings in a static extension method, so DI does not help us :(
ContentDeliveryNetworkExtensions.Configuration = new ContentDeliveryNetworkConfiguration(Configuration.GetSection("CDN"));
// Add MVC services to the services container
services.AddMvc();
//Add all SignalR related services to IoC.
services.AddSignalR();
//Add InMemoryCache
services.AddSingleton<IMemoryCache, MemoryCache>();
// Add session related services.
services.AddCaching();
services.AddSession();
}
示例8: ConfigureServices
// 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");
});
});
}
示例9: ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
RsaSecurityKey key;
// Obviously, hard coding the private key here is a horrendous idea - this should be passed in from
// some sort of configuration file supplied securely to the application. This is just to prove the
// concept of the auth strategy.
RSAParameters p = new RSAParameters()
{
Modulus = Convert.FromBase64String("z7eXmrs9z3Xm7VXwYIdziDYzXGfi3XQiozIRa58m3ApeLVDcsDeq6Iv8C5zJ2DHydDyc0x6o5dtTRIb23r5/ZRj4I/UwbgrwMk5iHA0bVsXVPBDSWsrVcPDGafr6YbUNQnNWIF8xOqgpeTwxrqGiCJMUjuKyUx01PBzpBxjpnQ++Ryz6Y7MLqKHxBkDiOw5wk9cxO8/IMspSNJJosOtRXFTR74+bj+pvNBa8IJ+5Jf/UfJEEjk+qC+pohCAryRk0ziXcPdxXEv5KGT4zf3LdtHy1YwsaGLnTb62vgbdqqCJaVyHWOoXsDTQBLjxNl9o9CzP6CrfBGK6JV8pA/xfQlw=="),
Exponent = Convert.FromBase64String("AQAB"),
P = Convert.FromBase64String("+VsETS2exORYlg2CxaRMzyG60dTfHSuv0CsfmO3PFv8mcYxglGa6bUV5VGtB6Pd1HdtV/iau1WR/hYXQphCP99Pu803NZvFvVi34alTFbh0LMfZ+2iQ9toGzVfO8Qdbj7go4TWoHNzCpG4UCx/9wicVIWJsNzkppSEcXYigADMM="),
Q = Convert.FromBase64String("1UCJ2WAHasiCdwJtV2Ep0VCK3Z4rVFLWg3q1v5OoOU1CkX5/QAcrr6bX6zOdHR1bDCPsH1n1E9cCMvwakgi9M4Ch0dYF5CxDKtlx+IGsZJL0gB6HhcEsHat+yXUtOAlS4YB82G1hZqiDw+Q0O8LGyu/gLDPB+bn0HmbkUC2kP50="),
DP = Convert.FromBase64String("CBqvLxr2eAu73VSfFXFblbfQ7JTwk3AiDK/6HOxNuL+eLj6TvP8BvB9v7BB4WewBAHFqgBIdyI21n09UErGjHDjlIT88F8ZtCe4AjuQmboe/H2aVhN18q/vXKkn7qmAjlE78uXdiuKZ6OIzAJGPm8nNZAJg5gKTmexTka6pFJiU="),
DQ = Convert.FromBase64String("ND6zhwX3yzmEfROjJh0v2ZAZ9WGiy+3fkCaoEF9kf2VmQa70DgOzuDzv+TeT7mYawEasuqGXYVzztPn+qHhrogqJmpcMqnINopnTSka6rYkzTZAtM5+35yz0yvZiNbBTFdwcuglSK4xte7iU828stNs/2JR1mXDtVeVvWhVUgCE="),
InverseQ = Convert.FromBase64String("Heo0BHv685rvWreFcI5MXSy3AN0Zs0YbwAYtZZd1K/OzFdYVdOnqw+Dg3wGU9yFD7h4icJFwZUBGOZ0ww/gZX/5ZgJK35/YY/DeV+qfZmywKauUzC6+DPsrDdW1uf1eAety6/huRZTduBFTwIOlPdZ+PY49j6S38DjPFNImn0cU="),
D = Convert.FromBase64String("IvjMI5cGzxkQqkDf2cC0aOiHOTWccqCM/GD/odkH1+A+/u4wWdLliYWYB/R731R5d6yE0t7EnP6SRGVcxx/XnxPXI2ayorRgwHeF+ScTxUZFonlKkVK5IOzI2ysQYMb01o1IoOamCTQq12iVDMvV1g+9VFlCoM+4GMjdSv6cxn6ELabuD4nWt8tCskPjECThO+WdrknbUTppb2rRgMvNKfsPuF0H7+g+WisbzVS+UVRvJe3U5O5X5j7Z82Uq6hw2NCwv2YhQZRo/XisFZI7yZe0OU2JkXyNG3NCk8CgsM9yqX8Sk5esXMZdJzjwXtEpbR7FiKZXiz9LhPSmzxz/VsQ==")
};
key = new RsaSecurityKey(p);
// Add the signing credentials so we can access them in the controller that doles out the tokens.
services.AddInstance(new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest));
// Configure the bearer token validation to use the supplied key, and validate the lifetime and signature when a
// key is supplied.
services.Configure<OAuthBearerAuthenticationOptions>(bearer =>
{
// Basic settings - signing key to validate with, audience and issuer.
bearer.TokenValidationParameters.IssuerSigningKey = key;
bearer.TokenValidationParameters.ValidAudience = TokenAudience;
bearer.TokenValidationParameters.ValidIssuer = TokenIssuer;
// When receiving a token, check that we've signed it.
bearer.TokenValidationParameters.ValidateSignature = true;
// When receiving a token, check that it is still valid.
bearer.TokenValidationParameters.ValidateLifetime = true;
// This defines the maximum allowable clock skew - i.e. provides a tolerance on the token expiry time
// when validating the lifetime. As we're creating the tokens locally and validating them on the same
// machines which should have synchronised time, this can be set to zero. Where external tokens are
// used, some leeway here could be useful.
bearer.TokenValidationParameters.ClockSkew = TimeSpan.FromMinutes(0);
});
// Enable the use of an [Authorize("Bearer")] attribute on methods and classes to protect.
services.ConfigureAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(OAuthBearerAuthenticationDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});
services.AddMvc();
}
示例10: ConfigureServices
// This method gets called by a runtime.
// Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole>(options => {
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc().Configure<MvcOptions>(options => {
var jsonFormatter = options.OutputFormatters.OfType<JsonOutputFormatter>().First();
jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
// 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();
// Bearer Token Stuff
#region Bearer Token Setup
RsaSecurityKey key;
RSACryptoServiceProvider publicAndPrivate = new RSACryptoServiceProvider();
var savykeyParams = JsonConvert.DeserializeObject<RSAParametersSerializable>(Configuration["rsa-key"]);
//This if is necessary because migrations don't find environment variables, and so we have to put a blank savy-rsa-key in the config file.
//That creates a null object. Thus the if.
if(savykeyParams != null) {
publicAndPrivate.ImportParameters(savykeyParams.RSAParameters);
key = new RsaSecurityKey(publicAndPrivate.ExportParameters(true));
services.AddInstance(new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest));
services.Configure<OAuthBearerAuthenticationOptions>(bearer => {
bearer.TokenValidationParameters.IssuerSigningKey = key;
bearer.TokenValidationParameters.ValidAudience = "mybearertokenapi";
bearer.TokenValidationParameters.ValidIssuer = "mybearertokenapi";
bearer.Notifications.AuthenticationFailed = async notification => {
if(notification.Exception.GetType() == typeof(SecurityTokenExpiredException)) {
//TODO: Figure out how to actually send a body. Just getting a 0-length 401 right now.
var message = "Access token expired.";
notification.HttpContext.Response.StatusCode = 401;
//notification.HttpContext.Response.ContentLength = message.Length * 2;
notification.HttpContext.Response.ContentType = "application/json; charset=utf-8";
await notification.HttpContext.Response.WriteAsync(message);
}
};
});
}
#endregion
services.AddScoped<IAuthRepository, AuthRepository>();
// Authorization policies
services.ConfigureAuthorization(auth => {
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(OAuthBearerAuthenticationDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build());
});
}
示例11: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddAuthorization();
services.ConfigureAuthorization(o => {
o.AddPolicy(Microsoft.Owin.Security.OAuth.OAuthDefaults.AuthenticationType,
new AuthorizationPolicyBuilder().AddAuthenticationSchemes(Microsoft.Owin.Security.OAuth.OAuthDefaults.AuthenticationType)
.RequireAuthenticatedUser()
.Build());
});
var container = new Container();
//services.AddMvc(options =>
//{
// foreach (var f in options.InputFormatters.OfType<JsonInputFormatter>())
// {
// f.SerializerSettings.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "dd-MM-yyyy" });
// f.SerializerSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
// f.SerializerSettings.Converters.Add(new IocCustomCreationConverter<IHelpContext>(container));
// }
// //options.ModelBinders.Insert(0, new IoCModelBinder<IHelpContext>(container, options.ModelBinders.ToArray()));
//});
//services.AddMvc()
services.AddMvc(options=> {
foreach (var f in options.InputFormatters.OfType<JsonInputFormatter>())
{
f.SerializerSettings.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "dd-MM-yyyy" });
f.SerializerSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
f.SerializerSettings.Converters.Add(new IocCustomCreationConverter<IHelpContext>(container));
}
foreach(var f in options.OutputFormatters.OfType<JsonOutputFormatter>())
{
var settings = f.SerializerSettings;
settings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
options.ModelBinders.Insert(0, new IoCModelBinder<IHelpContext>(container, options.ModelBinders.ToArray()));
});
container.Configure(x =>
{
x.Scan(scanning =>
{
scanning.Assembly(Assembly.GetExecutingAssembly());
scanning.WithDefaultConventions();
scanning.Convention<HelperResponseRegistrationConvention>();
scanning.AddAllTypesOf<IHelpContextProvider>();
});
AutoMapperConfiguration.Configure();
x.For<IMappingEngine>().Use(() => Mapper.Engine);
//x.AddRegistry<WebsiteRegistry>();
});
// Our framework extension point
container.Populate(services);
return container.GetInstance<IServiceProvider>();
}
示例12: ConfigureServices
// This method gets called by a runtime.
// Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
services.AddInstance(_signingCredentials);
services.AddMvc(options =>
{
options.Filters.Add(new GlobalExceptionHandler());
})
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
});
services.ConfigureOAuthBearerAuthentication(options =>
{
options.AutomaticAuthentication = true;
options.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = _key,
ValidAudience = _TokenAudience,
ValidIssuer = _TokenIssuer
};
});
services.ConfigureAuthorization(options =>
{
options.AddPolicy(
"Bearer",
new AuthorizationPolicyBuilder().
AddAuthenticationSchemes(OAuthBearerAuthenticationDefaults.AuthenticationScheme).
RequireAuthenticatedUser().
Build());
});
// 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();
}