【发布时间】:2021-12-20 08:49:12
【问题描述】:
我有一个托管在 Azure 中的 ASP.NET Core Web API。当我尝试从托管在 Vercell 上的网络应用发出获取请求时,我收到了以下错误:
CORS 政策已阻止从源“https://
{myapp}.vercel.app”获取{myapi enpoint}的访问权限:
对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
这是我的Startup.cs 文件:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Cors;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using Pomelo.EntityFrameworkCore.MySql;
using System.Threading.Tasks;
using ctsapi.Services;
using Jose;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using ctsapi.Models;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Http;
using System.Net;
namespace ctsapi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins", builder =>
{
builder.AllowAnyOrigin();
builder.AllowAnyMethod();
builder.AllowAnyHeader();
});
});
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "ctsapi", Version = "v1" });
//c.IncludeXmlComments(XmlCommentsPath.XmlCommentsFilePath);
});
var jwtSection = Configuration.GetSection("JWTSettings");
services.Configure<JWTSettings>(jwtSection);
//to validate the token which has been sent by clients
var appSettings = jwtSection.Get<JWTSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.SecretKey);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = true;
x.SaveToken = true;
x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddAuthorization(options =>
{
options.AddPolicy(Policies.Admin, Policies.AdminPolicy());
options.AddPolicy(Policies.ShopKeeper, Policies.ShopKeeperPolicy());
options.AddPolicy(Policies.User, Policies.UserPolicy());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseDefaultFiles();
app.UseStaticFiles(); // dodanie wwwroot
//if (env.IsDevelopment())
//{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ctsapi v1"));
//}
app.UseHttpsRedirection();
app.UseRouting();
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
{
// "Token Validation Has Failed. Request Access Denied"
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(new ErrorDto()
{
StatusCode = 401,
Message = "Token Validation Has Failed. Request Access Denied"
}.ToString());
}
});
app.UseCors("AllowAllOrigins");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
知道为什么会这样吗?
我的网络应用框架是 Next.js。
这是我的 Azure 配置:
- 默认部署配置文件(WebApp 托管在 F1 层的 Windows 机器上)
- 我什至更改了
web.config文件以始终发送所需的标头
【问题讨论】:
-
邮递员请求也很有效 - 邮递员不关心 CORS
-
这只是应该告诉端点没问题或smth的信息
-
在 Azure 管理门户中配置 CORS,而不是在您的代码中
-
我什至用 web.config 文件强制它,但 next.js 应用程序看不到它
-
看看这个答案....它解释了一些关于飞行前请求的事情。 stackoverflow.com/questions/69197165/…
标签: c# asp.net-core next.js asp.net-core-webapi