Nginx代理中的跨源预检请求

JB

从浏览器访问时出现此错误

从CORS策略阻止从原点“ https://example.com”访问“ https://api.example.com/users/authenticate”处的XMLHttpRequest:对预检请求的响应未通过访问控制检查:否请求的资源上存在“ Access-Control-Allow-Origin”标头

启动文件

using System;
using System.Text;
using BackendRest.Helper;
using BackendRest.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;

namespace BackendRest
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        readonly string CorsApi = "_CorsApi";
        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(CorsApi,
                    builder =>
                    {
                        builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader();
                    });
            });
            services.AddControllers().AddNewtonsoftJson();
            services.AddDbContext<backenddbContext>(x => x.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
            services.AddScoped<IUserHelper, UserHelper>();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ClockSkew = TimeSpan.Zero,
                    ValidateLifetime = true,
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidAudience = Configuration["Jwt:Audience"],
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseCors(CorsApi);
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Nginx Conf文件

server {
    #listen        80;
    listen                 *:443 ssl;
    ssl_certificate        /etc/ssl/example.com.pem;
    ssl_certificate_key    /etc/ssl/example.com.key;
    if ($host != "api.example.com") {
  return 404;
 }
    server_name            api.example.com;
    location / {
    proxy_pass      https://localhost:5001;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection keep-alive;
    proxy_cache_bypass $http_upgrade;
    proxy_set_header   X-Forwarded-Proto $scheme;
  }
}

还通过在控制器顶部添加以下代码在控制器中启用了Cors策略

[EnableCors(“ CorsApi”)]

在前端发送请求的功能:

export const login = async ({ username, password }) => {
  const result = await axios.post(
    `${BASE_URL}/users/authenticate`,
    JSON.stringify({ username, password }),
    {
      headers: {
        'Content-Type': 'application/json',
      },
    }
  );

  return result;
};

locahost服务器的启动设置:

"Kestrel": {
    "Endpoints": {
      "HTTPS": {
        "Url": "https://localhost:5001",
        "Certificate": {
          "Path": "/etc/ssl/example.pfx",
          "Password": "james343"
        }
      }
    }
  }

服务启动Locahost服务器:

[Unit]
Description=My first .NET Core application on Ubuntu

[Service]
WorkingDirectory=/home/ubuntu/example
ExecStart=/usr/bin/dotnet /home/ubuntu/example/BackendRest.dll
Restart=always
RestartSec=10 # Restart service after 10 seconds if dotnet service crashes
SyslogIdentifier=offershare-web-app
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
Environment=ASPNETCORE_HTTPS_PORT=5001
Environment=ASPNETCORE_URLS=https://localhost:5001

[Install]
WantedBy=multi-user.target

任何人都可以指出我在哪里出错了,这是新的Nginx内容,而使用普通iis托管的另一个项目都可以正常工作。

伊万·沙茨基(Ivan Shatsky)

我不知道是否可以从.NET应用程序本身添加CORS标头,或者这是一种更好的方法,但是要通过nginx添加它们,可以使用以下方法:

server {
    ...
    location / {
        if ($request_method = OPTIONS) {
            add_header Access-Control-Allow-Origin '*';
            add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
            add_header Content-Type text/plain;
            add_header Content-Length 0;
            return 204;
        }
        ... # your current configuration here
        add_header Access-Control-Allow-Origin '*';
        add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    }
}

如果需要支持其他方法(PUTDELETE等),请将它们添加到方法列表中。

更新资料

如果使用凭据创建XMLHttpRequest 则不能将其 *用作Access-Control-Allow-Origin标头值。在这种情况下,您可以动态将设置Access-Control-Allow-Origin为请求的Origin标头值:

server {
    ...
    location / {
        if ($request_method = OPTIONS) {
            add_header Access-Control-Allow-Origin $http_origin;
            add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
            add_header Content-Type text/plain;
            add_header Content-Length 0;
            return 204;
        }
        ... # your current configuration here
        add_header Access-Control-Allow-Origin $http_origin;
        add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

使用Apigee在预检请求中跨域Cookie

来自分类Dev

已完成401未授权请求被重定向到需要预检的跨域请求

来自分类Dev

Spring Data REST中的CORS预检请求

来自分类Dev

带有 axios 的 VueJS 中的预检请求

来自分类Dev

如何避免“预检请求”?

来自分类Dev

如何避免“预检请求”?

来自分类Dev

角度,对预检请求的响应

来自分类Dev

使用Spring MVC 4处理跨域预检AJAX OPTIONS请求

来自分类Dev

使用Spring MVC 4处理跨域预检AJAX OPTIONS请求

来自分类Dev

源已被 CORS 策略阻止对预检请求的响应未通过访问控制检查

来自分类Dev

是否可以将请求标头添加到CORS预检请求中?

来自分类Dev

无法调用我的api引发错误对于需要预检的跨域请求不允许

来自分类Dev

无法调用我的api引发错误对于需要预检的跨域请求不允许

来自分类Dev

允许在nginx上对laravel路由进行跨源请求

来自分类Dev

CORS预检请求返回HTTP 405

来自分类Dev

.NET Web API CORS预检请求

来自分类Dev

对预检请求的响应未通过?

来自分类Dev

选项预检导致 POST 请求挂起

来自分类Dev

跨源请求被阻止

来自分类Dev

跨源请求被阻止

来自分类Dev

AWS Lambda代理集成中的跨源资源共享

来自分类Dev

CORS预检请求在Azure托管的Web API中响应302重定向

来自分类Dev

有没有办法从ajax预检请求中获取调试信息?

来自分类Dev

XMLHttpRequest CORS到Google Cloud Storage仅在预检请求中起作用

来自分类Dev

无效的预检CORS请求,因为标头“ content-type”不在:allow_headers中

来自分类Dev

有没有办法在REST API Jersey中检测预检请求?

来自分类Dev

Codeigniter 4中的CORS问题:对预检请求的响应未通过访问控制检查

来自分类Dev

有没有办法从ajax预检请求中获取调试信息?

来自分类Dev

Spring CorsFilter似乎在预检请求中仍然收到401仍然无法正常工作

Related 相关文章

  1. 1

    使用Apigee在预检请求中跨域Cookie

  2. 2

    已完成401未授权请求被重定向到需要预检的跨域请求

  3. 3

    Spring Data REST中的CORS预检请求

  4. 4

    带有 axios 的 VueJS 中的预检请求

  5. 5

    如何避免“预检请求”?

  6. 6

    如何避免“预检请求”?

  7. 7

    角度,对预检请求的响应

  8. 8

    使用Spring MVC 4处理跨域预检AJAX OPTIONS请求

  9. 9

    使用Spring MVC 4处理跨域预检AJAX OPTIONS请求

  10. 10

    源已被 CORS 策略阻止对预检请求的响应未通过访问控制检查

  11. 11

    是否可以将请求标头添加到CORS预检请求中?

  12. 12

    无法调用我的api引发错误对于需要预检的跨域请求不允许

  13. 13

    无法调用我的api引发错误对于需要预检的跨域请求不允许

  14. 14

    允许在nginx上对laravel路由进行跨源请求

  15. 15

    CORS预检请求返回HTTP 405

  16. 16

    .NET Web API CORS预检请求

  17. 17

    对预检请求的响应未通过?

  18. 18

    选项预检导致 POST 请求挂起

  19. 19

    跨源请求被阻止

  20. 20

    跨源请求被阻止

  21. 21

    AWS Lambda代理集成中的跨源资源共享

  22. 22

    CORS预检请求在Azure托管的Web API中响应302重定向

  23. 23

    有没有办法从ajax预检请求中获取调试信息?

  24. 24

    XMLHttpRequest CORS到Google Cloud Storage仅在预检请求中起作用

  25. 25

    无效的预检CORS请求,因为标头“ content-type”不在:allow_headers中

  26. 26

    有没有办法在REST API Jersey中检测预检请求?

  27. 27

    Codeigniter 4中的CORS问题:对预检请求的响应未通过访问控制检查

  28. 28

    有没有办法从ajax预检请求中获取调试信息?

  29. 29

    Spring CorsFilter似乎在预检请求中仍然收到401仍然无法正常工作

热门标签

归档