azure删除了从我的应用程序服务返回的Access-Control-Allow-Origin标头 [英] azure removes Access-Control-Allow-Origin header returned from my app service

查看:80
本文介绍了azure删除了从我的应用程序服务返回的Access-Control-Allow-Origin标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  • 网络服务(角度应用程序/expressjs)
  • 应用服务(aspnet核心应用)

所有网络服务所做的只是向 app服务查询以下端点:my-app-service.azurewebsites.net/.well-known/openid-configuration

我的应用程序服务已设置为允许通过代码级通过IdentityServer4 dll来自我的网络服务的CORS请求,正如我在许多网站中提到的那样,我确保CORS设置都没有被 web.config azure 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

我忘记指定如果所有内容都在localhost上运行,则可以正常工作.但是它不在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

有什么提示吗?谢谢

解决方案

@NoName在此[...] 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"); } } }

Update #3 - CORS on Azure service app is not set

Any hints ? Thanks

解决方案

@NoName found the answer to my issue on this thread.

In a nutshell, https has to be enabled on Azure in order to work.

A warning from Azure in the logs would have been appreciated though. I wouldn't have lost days on this :S

这篇关于azure删除了从我的应用程序服务返回的Access-Control-Allow-Origin标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆