简体   繁体   English

如何转换请求 header 以便我不会遇到 CORS 错误?

[英]How to transform request header such that I don't run into CORS error?

I currently have a site which take in all ingoing request and forward them to the correct website.我目前有一个网站可以接收所有传入的请求并将它们转发到正确的网站。

This is currently setup via this Yarp configuration:这是当前通过此 Yarp 配置设置的:

 { "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "ReverseProxy": { "Routes": { "server": { "ClusterId": "old-site", "Match": { "Path": "{**catch-all}" } }, "azure": { "ClusterId": "new-site", "Match": { "Path": "yarpb" } } }, "Clusters": { "old-site": { "Destinations": { "server": { "Address": "https://test-www.a.com/" } } }, "new-site": { "Destinations": { "yarpb": { "Address": "https://example.com/" } } } } } }

The entry point is test.a.com and which according to the redirect rule above will redirect to test-www.a.com.入口点是 test.a.com,根据上面的重定向规则,它会重定向到 test-www.a.com。

This is fine, and works as it is supposed.这很好,并且可以按预期工作。

One site that seems problematic now is the cms backoffice umbraco, test.a.com/umbraco, which sometimes fetches files from the app_plugins folder.现在似乎有问题的一个站点是 cms backoffice umbraco,test.a.com/umbraco,它有时会从 app_plugins 文件夹中获取文件。

Some of these files are fetched with CORS其中一些文件是使用 CORS 获取的

在此处输入图像描述

which is causing an issue when the original html request is being redirected to a different page.当原始 html 请求被重定向到不同页面时,这会导致问题。 在此处输入图像描述

Is it somehow possible let it pass through?有没有可能让它通过?

I have in the code tried this app.UseCors(x => x.AllowAnyOrigin());我在代码中试过这个app.UseCors(x => x.AllowAnyOrigin()); but it does not seem to change anything?但它似乎并没有改变什么?

its like this is being set after yarp redirect the request as yarp logging states 200 response, but the browser says 405 ?在 yarp 将请求重定向为 yarp 记录状态200响应后设置它,但浏览器显示405

Log snippet:日志片段:

 2022-06-21T17:48:02.6237461+02:00 INFO [Yarp.ReverseProxy.Forwarder.HttpForwarder] [Forwarding] Proxying to https://test-www.a.com/App_Plugins/RJP.MultiUrlPicker/MultiUrlPicker.html HTTP/2 RequestVersionOrLower no-streaming 2022-06-21T17:48:02.6255128+02:00 INFO [Yarp.ReverseProxy.Forwarder.HttpForwarder] [ResponseReceived] Received HTTP/2.0 response 301. 2022-06-21T17:48:02.6256100+02:00 INFO [ReverseProxy.Middleware.RequestResponseLoggerMiddleware] [LogRequest] https://test.a.com/App_Plugins/RJP.MultiUrlPicker/MultiUrlPicker.html proxied to https://test-www.a.com//App_Plugins/RJP.MultiUrlPicker/MultiUrlPicker.html 2022-06-21T17:48:02.6273081+02:00 INFO [Yarp.ReverseProxy.Forwarder.HttpForwarder] [ResponseReceived] Received HTTP/2.0 response 200.

entire program.cs整个程序.cs

 var builder = WebApplication.CreateBuilder(args); builder.Services.AddReverseProxy().LoadFromConfig(builder.Configuration.GetSection("ReverseProxy")); builder.Services.AddLogging(x => { x.AddJsonConsole(); x.AddFile($"logs/app-{DateTime.UtcNow:yyyyMMddHHmmss}.log", append: true); }); var app = builder.Build(); app.UseStaticFiles(); app.UseRouting(); app.UseCors(x => x.AllowAnyOrigin()); app.MapReverseProxy(proxyPipeline => { proxyPipeline.UseRequestResponseLogging(); }); app.Run();

So after some investigation i finally managed to fix the issue via yarp, by modifiying the response header location to be the same as the request header.因此,经过一番调查,我终于设法通过 yarp 解决了这个问题,方法是将响应 header 位置修改为与请求 header 相同。

 .AddTransforms(builderContext => { builderContext.AddResponseTransform(async context => { if (context.HttpContext.Response.StatusCode == 302 || context.HttpContext.Response.StatusCode == 301) { if (context.ProxyResponse == null) { return; } var proxyResponse = context.ProxyResponse.Headers; var oldLocation = context.HttpContext.Response.GetTypedHeaders().Location; if (oldLocation == null) { return; } var oldLocationScheme = oldLocation.Scheme; var oldLocationHost = oldLocation.Host; var oldLocationsPath = oldLocation.AbsolutePath; var newLocation = new UriBuilder() { Scheme = oldLocationScheme, Host = oldLocationHost, Path = oldLocationsPath }.Uri; context.HttpContext.Response.GetTypedHeaders().Location = proxyResponse.Location = newLocation; context.SuppressResponseBody = true; } });

From the documentation it seems that you need to map your entries to use CORS by calling RequireCors method.文档看来,您需要 map 您的条目才能通过调用RequireCors方法来使用 CORS。

It also seems that it is better for you to construct a policy, add the desired origins to that policy and then map your entries to the policy.似乎您最好构建一个策略,将所需的来源添加到该策略中,然后 map 将您的条目添加到该策略中。 That way - any change to the policy will immediately affect all registered end-points.这样 - 对策略的任何更改都将立即影响所有已注册的端点。

Also, beware that when you are using a wildcard inside your CORS config, you may disable other functionality in modern browsers ( MDN to the rescue).另外,请注意,当您在 CORS 配置中使用通配符时,您可能会禁用现代浏览器中的其他功能(救命MDN )。 So please - try to specify your own domain to ensure everything works as excepted所以请 - 尝试指定您自己的域,以确保一切正常

Add following in Configure配置中添加以下内容

app.UseCors(options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials());

Add this to service in ConfigureServices:将此添加到 ConfigureServices 中的服务:

 services.AddCors(options => { options.AddDefaultPolicy( builder => { builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod(); }); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM