【发布时间】:2018-12-02 06:44:23
【问题描述】:
我基本上遵循了这个文档:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1 试图在我的项目中正确设置它,但到目前为止还没有缺乏。我想我尝试了每一种组合,包括中间和服务、更改顺序等。
使用邮递员进行测试时,在对我的 API 端点进行 POST 调用时,我看不到任何与 CORS 相关的标头。
我正在使用 API 并在 http:/localhost:3000 上运行的应用在尝试对 API 端点进行 POST 调用时出现 CORS 错误。
这是我的整个Startup.cs 课程:
public class Startup
{
public Startup(IHostingEnvironment hostingEnvironment, IConfiguration configuration)
{
HostingEnvironment = hostingEnvironment;
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public IHostingEnvironment HostingEnvironment { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddInjectionByAttribute();
services.AddDbContext<MoneyTrackigContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<UserContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("UserDbConnection")));
services.AddIdentity<IdentityUser, IdentityRole>(o =>
{
o.Password.RequireDigit = false;
o.Password.RequiredLength = 6;
o.Password.RequireLowercase = false;
o.Password.RequireNonAlphanumeric = false;
o.Password.RequireUppercase = false;
})
.AddEntityFrameworkStores<UserContext>()
.AddDefaultTokenProviders();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = HostingEnvironment.IsDevelopment();
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = Configuration.GetSection("JwtOptions")["JwtIssuer"],
ValidAudience = Configuration.GetSection("JwtOptions")["JwtIssuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("JwtOptions")["JwtKey"])),
ClockSkew = TimeSpan.Zero // remove delay of token when expire
};
});
services.AddAuthorization(o =>
{
o.AddPolicy(Policy.DefaultUser, policy => policy.RequireClaim(ClaimName.User));
});
services.AddAutoMapper();
services.AddCors();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseCors(b => b.WithOrigins("http:/localhost:3000").AllowAnyHeader().AllowAnyMethod());
app.UseMvc();
}
}
我是否遗漏了一些明显的东西?任何可能导致此问题的想法。整个事情看起来很简单,但被卡住了。
【问题讨论】:
-
对于遇到此问题的任何人,在设置原点的“b.WithOrigins”中的协议中缺少一个斜线。
标签: .net asp.net-core cors .net-core asp.net-core-mvc