azure 删除从我的应用服务返回的 Access-Control-Allow-Origin 标头

Posted

技术标签:

【中文标题】azure 删除从我的应用服务返回的 Access-Control-Allow-Origin 标头【英文标题】:azure removes Access-Control-Allow-Origin header returned from my app service 【发布时间】:2018-06-15 13:53:23 【问题描述】:

我在 Azure 上运行了两个服务:

一个网络服务(angular app / expressjs) 应用服务(aspnet核心应用)

web 服务 所做的只是查询 app 服务 以获取以下端点:my-app-service.azurewebsites.net/.well-known/openid-configuration

我的 应用服务 设置为允许通过 IdentityServer4 dll 在代码级别来自我的 Web 服务 的 CORS 请求,正如在许多网站中提到的那样,我确实确保了 CORS 设置既没有被 web.configazure CORS 管理页面覆盖。

这些是我的 HTTP 请求标头:

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Host:my-app-service.azurewebsites.net
Origin:http://my-web-service.azurewebsites.net
Pragma:no-cache
Referer:http://my-web-service.azurewebsites.net/

这些是我的 HTTP 响应标头

Content-Encoding:gzip
Content-Type:application/json
Date:Fri, 05 Jan 2018 17:22:53 GMT
Server:Kestrel
Set-Cookie:ARRAffinity=da4c4ff244aae03ae3c7548f243f7c2b5c22567a56a76a62aaebc44acc7f0ba8;Path=/;HttpOnly;Domain=Host:my-app-service.azurewebsites.net
Transfer-Encoding:chunked
Vary:Accept-Encoding
X-Powered-By:ASP.NET

如您所见,Access-Control-* 标头都不存在。我在 asp.net 核心应用程序管道中添加了一个自定义中间件来跟踪响应标头,我可以清楚地看到它们存在。

所以 Azure 在某处剥离了我的标题,而我现在不知道该去哪里找。


更新 #1

我忘了说明如果一切都在本地主机上运行,​​它工作正常。但它不在 Azure 上。

更新 #2

我的身份服务器 4 代码

[...]
using Microsoft.IdentityModel.Tokens;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4;

namespace My.IdentityServer4

    public class Startup
    
        private const string DEFAULT_DEVELOPMENT_AUTHORITY = "http://localhost:5000/";

        public Startup(IConfiguration configuration)
        
            Configuration = configuration;
        

        public IConfiguration Configuration  get; 

        public void ConfigureServices(IServiceCollection services)
        
            // [... add db context. identity framework, default token provider]
            services.AddMvc();

            // Cors ( not required, identity server 4 manages it internally )
            //services.AddCors(options =>
            //    options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));

            string connectionString = Configuration.GetConnectionString("SQLServer");
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            // configure identity server with in-memory stores, keys, clients and scopes
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddAspNetIdentity<ApplicationUser>()
                // this adds the config data from DB (clients, resources)
                .AddConfigurationStore(options =>
                
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(connectionString,
                            sql => sql.MigrationsAssembly(migrationsAssembly));
                )
                // this adds the operational data from DB (codes, tokens, consents)
                .AddOperationalStore(options =>
                
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(connectionString,
                            sql => sql.MigrationsAssembly(migrationsAssembly));

                    // this enables automatic token cleanup. this is optional.
                    options.EnableTokenCleanup = true;
                    options.TokenCleanupInterval = 30;
                );

            services.AddAuthentication()
                .AddOpenIdConnect("oidc", "OpenID Connect", options =>
                
                    //TODO: enable HTTPS for production
                    options.RequireHttpsMetadata = false;
                    options.Authority = DEFAULT_DEVELOPMENT_AUTHORITY;
                    options.ClientId = "app"; // implicit
                    options.SaveTokens = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    
                        NameClaimType = "name",
                        RoleClaimType = "role"
                    ;
                );
        

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        
            // [... Some stuff before not useful for this snippet]

            // For debug purposes, print out request and response headers
            app.UseMiddleware<LogHeadersMiddleware>();

            app.UseStaticFiles();

            // Cors ( not required, identity server 4 manages it internally )
            //app.UseCors("AllowAllOrigins");

            app.UseIdentityServer();

            app.UseMvc(routes =>
            
                routes.MapRoute(
                    name: "default",
                    template: "controller=Home/action=Index/id?");
            );
        
    



    public class LogHeadersMiddleware
    
        private readonly RequestDelegate next;
        private readonly ILogger<LogHeadersMiddleware> logger;

        public LogHeadersMiddleware(RequestDelegate next, ILogger<LogHeadersMiddleware> logger)
        
            this.next = next;
            this.logger = logger;
        

        public async Task Invoke(HttpContext context)
        
            await this.next.Invoke(context);

            logger.LogInformation(
                $"------------------------\r\n" +
                $"*** Request headers ****\r\n" +
                string.Join("\r\n", context.Request.Headers.OrderBy(x => x.Key)) + "\r\n" +
                $"*** Response headers ***\r\n" +
                string.Join("\r\n", context.Response.Headers.OrderBy(x => x.Key)) + "\r\n" +
                $"------------------------\r\n");

        
    

更新 #3 - Azure 服务应用程序上的 CORS 未设置

有什么提示吗?谢谢

【问题讨论】:

发布您的代码...它将帮助我们帮助您。 嗨@ElmerDantas,我确实发布了一些代码,但我不确定它是否与问题相关。我忘了指定在本地主机上运行时一切正常! 【参考方案1】:

@NoName 在thread 上找到了我的问题的答案。

简而言之,必须在 Azure 上启用 https 才能工作。

如果 Azure 在日志中发出警告,我们将不胜感激。我不会为此浪费几天的时间:S

【讨论】:

【参考方案2】:

Azure 服务应用上的 CORS 未设置。

实际上,Azure 网站应该为您管理 CORS。您只需要在 Azure 服务 App 上设置 CORS。我还找到了一个类似的SO thread。

好消息是您可以完全禁用此中间件并通过自己的方式管理 CORS,您只需从门户中的 CORS 设置刀片中删除每个允许的来源(包括 *)。

【讨论】:

感谢您花时间查看它。正如我所说,我不想通过 Azure 刀片管理 CORS,因此我的屏幕截图没有任何价值(更新 #3)。我想让identityserver4通过自己的配置表来管理它。 如果 Azure 门户 CORS 中没有值表示不从服务器端开启支持 CORS。如果我们想使用 CORS,它是必需的。 这来自你给我的链接:you just have to remove every single allowed origin (including *) from the CORS settings blade in the portal. Then you can use web.config or Web Api to handle it more specifically。这意味着如果我不在 azure 界面上配置它,它将让我的应用程序处理它。还是我理解错了? 抱歉让您误会了。根据我的经验,您可以使用 web.config 做到这一点。它还将映射到服务器端设置。 这似乎不是 aspnet 核心链接。但无论如何,在我的情况下,CORS 是通过 IdentityServer4 代码(github.com/IdentityServer/IdentityServer4/blob/…)启用的

以上是关于azure 删除从我的应用服务返回的 Access-Control-Allow-Origin 标头的主要内容,如果未能解决你的问题,请参考以下文章

从 azure storage mvc 中删除 Blob

如何从我的应用程序中删除新的返回上一个应用程序 iOS 9 按钮?

是否可以仅使用用户从我的 .net 核心应用程序登录 Azure 并通过?

我无法从我的 REACT 应用程序中读取 azure 应用程序服务配置中的环境变量

Azure 移动应用程序:无法从我的 nodeJS 后端发送推送通知

从我的浏览器连接到 Azure Service Fabric 集群中托管的服务时出错