C# ASP核心API 2.2。RequireRecall和RequireAuthenticatedUser策略不起作用
ASP核心2.2 API。我有两项政策:C# ASP核心API 2.2。RequireRecall和RequireAuthenticatedUser策略不起作用,c#,.net,asp.net-core,.net-core,asp.net-identity,C#,.net,Asp.net Core,.net Core,Asp.net Identity,ASP核心2.2 API。我有两项政策: services.AddAuthorization(options => { options.AddPolicy("RequireClientClaim", policy => policy.RequireAuthenticatedUser().RequireClaim("Client")); options.AddPolicy("AllAuthenticated", polic
services.AddAuthorization(options => {
options.AddPolicy("RequireClientClaim", policy => policy.RequireAuthenticatedUser().RequireClaim("Client"));
options.AddPolicy("AllAuthenticated", policy => policy.RequireAuthenticatedUser());
});
“RequireClientClaim”不允许任何用户使用客户端声明。声明取自数据库并添加到JWT令牌中。令牌通过授权发送回:承载xxxx头。我可以在context.HttpContext.user.Claims中的下一个用户请求中看到此声明:
“AllAuthenticated”允许所有人:)所以我猜这里有些东西很不好
[HttpPost, Route("refresh")]
[Authorize(Policy = "AllAuthenticated")]
public async Task<IActionResult> ActionName(){}
[HttpPost,路由(“刷新”)]
[授权(Policy=“AllAuthenticated”)]
公共异步任务ActionName(){}
我没有在筛选器中放置任何策略,因为我的策略不打算应用于所有控制器和操作。
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Linq;
using System.IO.Compression;
using System.Text;
using Scrutor;
using MediatR;
using System.Reflection;
using xxxxxxx.Features.shared;
using Newtonsoft.Json.Serialization;
using Swashbuckle.AspNetCore.Swagger;
using System.IO;
using Microsoft.AspNetCore.Rewrite;
using System.Globalization;
using Microsoft.AspNetCore.Localization;
using System.Collections.Generic;
using AspNetCore.Identity.Dapper;
using Microsoft.AspNetCore.Identity;
using ConnectionsManager;
namespace xxxxxx
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddNodeServices(options =>
{
options.ProjectPath = Path.Combine(Directory.GetCurrentDirectory(), "App");
});
services.AddLazyCache();
services.AddResponseCompression();
services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Fastest;
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = null,
ValidAudience = null,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("xxxxxxxxx"))
};
});
services.AddCors(options =>
{
options.AddPolicy("EnableCORS", builder =>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials().Build();
});
});
var connectionString = DbConnectionsManager.GetConnectionStringToSqlDB();
services.Configure<IdentityOptions>(options => {
options.Password.RequireDigit = false;
options.Password.RequiredLength = 4;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789, -._@+ñÑçÇäëïöüâêîôûáéíóúàèìòùÄËÏÖÜÂÊÎÔÛÁÉÍÓÚÀÈÌÒÙ";
});
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddUserManager<UserManager<ApplicationUser>>()
.AddRoles<ApplicationRole>()
.AddRoleManager<RoleManager<ApplicationRole>>()
.AddSignInManager<SignInManager<ApplicationUser>>()
.AddDapperStores(connectionString)
.AddDefaultTokenProviders();
services.AddMvc(config =>
{
config.Filters.Add<CurrentUserFilter>();
config.Filters.Add(new UserLanguageFilter());
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.AddAuthorization(options => {
options.AddPolicy("RequireClientClaim", policy => policy.RequireAuthenticatedUser().RequireClaim("Client"));
options.AddPolicy("AllAuthenticated", policy => policy.RequireAuthenticatedUser());
});
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "App/dist";
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "XXXXXXXXX", Version = "v1" });
});
services.Scan(scan => scan
.FromAssembliesOf(typeof(SapViewsProxyDBLoaders.SimilarItemsSapViewLoader))
.AddClasses()
.UsingRegistrationStrategy(RegistrationStrategy.Skip)
.AsImplementedInterfaces()
.WithSingletonLifetime());
services.Scan(scan => scan
.FromCallingAssembly()
.AddClasses()
.UsingRegistrationStrategy(RegistrationStrategy.Skip)
.AsImplementedInterfaces()
.WithTransientLifetime());
services.Scan(scan => scan
.FromAssembliesOf(typeof(SapDataProvider.SapDataProvider),
typeof(ConnectionsManager.SapConfiguration),
typeof(FeaturesLogs.Products.PriceRequestLogger))
.AddClasses()
.UsingRegistrationStrategy(RegistrationStrategy.Skip)
.AsImplementedInterfaces()
.WithTransientLifetime());
services.AddMediatR(typeof(Startup).GetTypeInfo().Assembly);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseResponseCompression();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseAuthentication();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "xxxx");
});
var defaultDateCulture = "es-ES";
var ci = new CultureInfo(defaultDateCulture);
ci.NumberFormat.NumberDecimalSeparator = ".";
ci.NumberFormat.CurrencyDecimalSeparator = ".";
// Configure the Localization middleware
app.UseRequestLocalization(new RequestLocalizationOptions {
DefaultRequestCulture = new RequestCulture(ci),
SupportedCultures = new List<CultureInfo>
{
ci,
},
SupportedUICultures = new List<CultureInfo>
{
ci,
}
});
app.UseRewriter(new RewriteOptions()
.AddRedirect("index.html", "/"));
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseCors("EnableCORS");
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
spa.UseSpaPrerendering(options =>
{
options.BootModulePath = $"{spa.Options.SourcePath}/dist-server/main.js";
options.BootModuleBuilder = env.IsDevelopment()
? new AngularCliBuilder(npmScript: "build:ssr")
: null;
options.ExcludeUrls = new[] { "/sockjs-node" };
});
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
}
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.AspNetCore.SpaServices.AngularCli;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.AspNetCore.ResponseCompression;
使用Microsoft.IdentityModel.Tokens;
使用Microsoft.AspNetCore.Authentication.JwtBearer;
使用System.Linq;
使用系统IO压缩;
使用系统文本;
使用Scrutor;
使用MediatR;
运用系统反思;
使用xxxxxxx.Features.shared;
使用Newtonsoft.Json.Serialization;
使用swashback.AspNetCore.Swagger;
使用System.IO;
使用Microsoft.AspNetCore.Rewrite;
利用制度全球化;
使用Microsoft.AspNetCore.Localization;
使用System.Collections.Generic;
使用AspNetCore.Identity.Dapper;
使用Microsoft.AspNetCore.Identity;
使用连接管理器;
名称空间xxxxxx
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
public void配置服务(IServiceCollection服务)
{
服务。添加节点服务(选项=>
{
options.ProjectPath=Path.Combine(Directory.GetCurrentDirectory(),“App”);
});
services.AddLazyCache();
services.AddResponseCompression();
配置(选项=>
{
选项。级别=压缩级别。最快;
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(选项=>
{
options.TokenValidationParameters=新的TokenValidationParameters
{
validateisuer=true,
ValidateAudience=true,
ValidateLifetime=true,
ValidateSuersigningKey=true,
ValidIssuer=null,
Validudience=null,
IssuerSigningKey=新的SymmetricSecurityKey(Encoding.UTF8.GetBytes(“xxxxxxxx”))
};
});
services.AddCors(选项=>
{
options.AddPolicy(“EnableCORS”,builder=>
{
builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials().Build();
});
});
var connectionString=DbConnectionsManager.GetConnectionStringToSqlDB();
配置(选项=>{
options.Password.RequireDigit=false;
options.Password.RequiredLength=4;
options.Password.RequireNonAlphanumeric=false;
options.Password.RequireUppercase=false;
options.Password.RequireLowercase=false;
options.User.AllowedUserNameCharacters=“abcdefghijklmnopqrstuvxyzedefghijklmnopqrstuvxyz012456789-。”;
});
服务.额外性()
.AddUserManager()
.AddRoles()
.AddRoleManager()
.AddSignInManager()的名称
.AddDapperStores(连接字符串)
.AddDefaultTokenProviders();
services.AddMvc(配置=>
{
config.Filters.Add();
添加(新的UserLanguageFilter());
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(options=>options.SerializerSettings.ContractResolver=new DefaultContractResolver());
services.AddAuthorization(选项=>{
options.AddPolicy(“RequireClientClaim”,policy=>policy.RequireAuthenticatedUser().requireReclaim(“客户端”);
options.AddPolicy(“AllAuthenticated”,policy=>policy.RequireAuthenticatedUser());
});
services.AddSpaStaticFiles(配置=>
{
configuration.RootPath=“App/dist”;
});
services.AddSwaggerGen(c=>
{
c、 虚张声势的文件(“v1”,新信息{Title=“XXXXXXXXX”,Version=“v1”});
});
services.Scan(Scan=>Scan
.FromAssembliesOf(类型(SapViewsProxyDBLoaders.SimilarItemsSapViewLoader))
.AddClasses()
.使用RegistrationStrategy(RegistrationStrategy.Skip)
.AsImplementedInterfaces()
.使用SingleTonlifetime());
services.Scan(Scan=>Scan
.FromCallingAssembly()
.AddClasses()
.使用RegistrationStrategy(RegistrationStrategy.Skip)
.AsImplementedInterfaces()
.WithTransientLifetime());
services.Scan(Scan=>Scan
.FromAssembliesOf(类型)(SapDataProvider.SapDa
public AuthorizationPolicyBuilder RequireClaim(string claimType, params string[] requiredValues);
options.AddPolicy("RequireClientClaim", policy => policy.RequireClaim(ClaimTypes.Role, "Client"));