如何解决No' Access-Control-Allow-Origin'标头出现在ASP.NET Boilerplate中请求的资源上?

时间:2017-12-15 16:12:27

标签: asp.net-core asp.net-core-2.0 aspnetboilerplate

我正在使用ASP.NET Boilerplate框架开发Web应用程序,该框架基于asp.net core 2.0。 访问http://localhost:4200时,我在浏览器控制台中收到以下错误。

  

2:22742 / AbpUserConfiguration / GetAll:1 GET   http://localhost:22742/AbpUserConfiguration/GetAll 500(内部   服务器错误)localhost /:1无法加载   http://localhost:22742/AbpUserConfiguration/GetAll:不   '访问控制允许来源'标题出现在请求的上   资源。起源' http://localhost:4200'因此是不允许的   访问。响应的HTTP状态代码为500。

Logs.txt内容:

  

INFO 2017-12-14 17:38:21,091 [21]   soft.AspNetCore.Hosting.Internal.WebHost - 请求启动HTTP / 1.1   选项http://localhost:22742/AbpUserConfiguration/GetAll信息   2017-12-14 17:38:21,148 [21] pNetCore.Cors.Infrastructure.CorsService    - 政策执行成功。 INFO 2017-12-14 17:38:21,589 [21] soft.AspNetCore.Hosting.Internal.WebHost - 请求已完成   416.2933ms 204 INFO 2017-12-14 17:38:22,414 [21] soft.AspNetCore.Hosting.Internal.WebHost - 请求启动HTTP / 1.1   获取http://localhost:22742/AbpUserConfiguration/GetAll   application / json INFO 2017-12-14 17:38:22,597 [21]   pNetCore.Cors.Infrastructure.CorsService - 策略执行   成功的。 INFO 2017-12-14 17:38:22,644 [21]   uthentication.JwtBearer.JwtBearerHandler - 成功验证了   令牌。 INFO 2017-12-14 17:38:22,694 [21]   uthentication.JwtBearer.JwtBearerHandler - AuthenticationScheme:   Bearer已成功通过身份验证。 INFO 2017-12-14 17:38:22,737   [21] pNetCore.Cors.Infrastructure.CorsService - 策略执行   成功的。 INFO 2017-12-14 17:38:22,849 [21]   ore.Mvc.Internal.ControllerActionInvoker - 执行动作方法   Abp.AspNetCore.Mvc.Controllers.AbpUserConfigurationController.GetAll   (Abp.AspNetCore)带参数((null)) - ModelState是有效INFO   2017-12-14 17:38:32,529 [23]事项.Json.Internal.JsonResultExecutor    - 执行JsonResult,写入值Abp.Web.Models.AjaxResponse。 INFO 2017-12-14 17:38:32,541 [23]   ore.Mvc.Internal.ControllerActionInvoker - 执行的动作   Abp.AspNetCore.Mvc.Controllers.AbpUserConfigurationController.GetAll   (Abp.AspNetCore)9816.8741ms INFO 2017-12-14 17:38:32,554 [23]   soft.AspNetCore.Hosting.Internal.WebHost - 请求已完成   10382.9474ms 200 application / json; charset = utf-8 INFO 2017-12-14 17:38:32,926 [14] soft.AspNetCore.Hosting.Internal.WebHost - Request   启动HTTP / 1.1选项http://localhost:22742/api/services/app ...   编队INFO 2017-12-14 17:38:32,927 [14]   pNetCore.Cors.Infrastructure.CorsService - 策略执行   成功的。 INFO 2017-12-14 17:38:32,941 [14]   soft.AspNetCore.Hosting.Internal.WebHost - 请求已完成   4.2417ms 204 INFO 2017-12-14 17:38:32,948 [14] soft.AspNetCore.Hosting.Internal.WebHost - 请求启动HTTP / 1.1   获得http://localhost:22742/api/services/app ......阵型   application / json INFO 2017-12-14 17:38:32,950 [14]   pNetCore.Cors.Infrastructure.CorsService - 策略执行   成功的。 INFO 2017-12-14 17:38:32,957 [14]   uthentication.JwtBearer.JwtBearerHandler - 成功验证了   令牌。 INFO 2017-12-14 17:38:32,960 [14]   uthentication.JwtBearer.JwtBearerHandler - AuthenticationScheme:   Bearer已成功通过身份验证。 INFO 2017-12-14 17:38:32,968   [14] pNetCore.Cors.Infrastructure.CorsService - 策略执行   成功的。 INFO 2017-12-14 17:38:33,004 [14]   ore.Mvc.Internal.ControllerActionInvoker - 执行动作方法   Nec.Stanchion.Sessions.SessionAppService.GetCurrentLoginInformations   (Nec.Stanchion.Application)带参数((null)) - ModelState是   有效错误2017-12-14 17:38:33,466 [21]   Mvc.ExceptionHandling.AbpExceptionFilter - 没有当前用户!   System.Exception:没有当前用户!在   Nec.Stanchion.StanchionAppServiceBase.d__9.MoveNext()   在   C:\ Users \用户viveknuna \源\回购\支柱\ ASPNET核\ SRC \ Nec.Stanchion.Application \ StanchionAppServiceBase.cs:线   36   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Abp.Threading.InternalAsyncHelper.d__5 1.MoveNext() in D:\Github\aspnetboilerplate\src\Abp\Threading\InternalAsyncHelper.cs:line 120 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter 1.GetResult()at   Nec.Stanchion.Sessions.SessionAppService.d__0.MoveNext()   在   C:\ Users \ viveknuna \ source \ repos \ Stanchion \ aspnet-core \ src \ Nec.Stanchion.Application \ Sessions \ SessionAppService.cs:第44行   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)在lambda_method(Closure,Object)at   Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()   在   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__12.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__10.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext   上下文)   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(州及放大器;   接下来,范围&范围,对象& state,Boolean& isCompleted)at   Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__14.MoveNext()   ---从抛出异常的先前位置开始的堆栈跟踪结束--- at   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务   任务)   Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__23.MoveNext()   INFO 2017-12-14 17:38:33,473 [21]   etCore.Mvc.Internal.ObjectResultExecutor - 执行ObjectResult,   写作值Microsoft.AspNetCore.Mvc.ControllerContext。信息   2017-12-14 17:38:33,494 [21] ore.Mvc.Internal.ControllerActionInvoker    - 执行的操作Nec.Stanchion.Sessions.SessionAppService.GetCurrentLoginInformations   (Nec.Stanchion.Application)在505.7051ms INFO 2017-12-14 17:38:33,707   [21] soft.AspNetCore.Hosting.Internal.WebHost - 请求已完成   588.0669ms 500 application / json;字符集= UTF-8

Startup.cs:

using System;
using System.Linq;
using Abp.AspNetCore;
using Abp.AspNetZeroCore.Web.Authentication.JwtBearer;
using Abp.Castle.Logging.Log4Net;
using Abp.Dependency;
using Abp.Extensions;
using Abp.Hangfire;
using Abp.Timing;
using Castle.Facilities.Logging;
using Hangfire;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MyCompany.MyProject.Authorization;
using MyCompany.MyProject.Authorization.Roles;
using MyCompany.MyProject.Authorization.Users;
using MyCompany.MyProject.Configuration;
using MyCompany.MyProject.EntityFrameworkCore;
using MyCompany.MyProject.Identity;
using MyCompany.MyProject.Install;
using MyCompany.MyProject.MultiTenancy;
using MyCompany.MyProject.Web.Authentication.JwtBearer;
using PaulMiami.AspNetCore.Mvc.Recaptcha;
using Swashbuckle.AspNetCore.Swagger;
using MyCompany.MyProject.Web.IdentityServer;
#if FEATURE_SIGNALR
using Abp.Owin;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Cors;
using Owin;
using Owin.Security.AesDataProtectorProvider;
using Abp.Web.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Abp.AspNetZeroCore.Web.Owin;
#endif

namespace MyCompany.MyProject.Web.Startup
{
    public class Startup
    {
        private const string DefaultCorsPolicyName = "localhost";

        private readonly IConfigurationRoot _appConfiguration;

        public Startup(IHostingEnvironment env)
        {
            _appConfiguration = env.GetAppConfiguration();
        }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //MVC
            services.AddMvc(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory(DefaultCorsPolicyName));
            });

            //Configure CORS for angular2 UI
            services.AddCors(options =>
            {
                options.AddPolicy(DefaultCorsPolicyName, builder =>
                {
                    //App:CorsOrigins in appsettings.json can contain more than one address with splitted by comma.
                    builder
                        //.WithOrigins(_appConfiguration["App:CorsOrigins"].Split(",", StringSplitOptions.RemoveEmptyEntries).Select(o => o.RemovePostFix("/")).ToArray())
                        .AllowAnyOrigin() //TODO: Will be replaced by above when Microsoft releases microsoft.aspnetcore.cors 2.0 - https://github.com/aspnet/CORS/pull/94
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
            });

            IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, _appConfiguration);

            //Identity server
            if (bool.Parse(_appConfiguration["IdentityServer:IsEnabled"]))
            {
                IdentityServerRegistrar.Register(services, _appConfiguration);
            }

            //Swagger - Enable this line and the related lines in Configure method to enable swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info { Title = "MyProject API", Version = "v1" });
                options.DocInclusionPredicate((docName, description) => true);
            });

            //Recaptcha
            services.AddRecaptcha(new RecaptchaOptions
            {
                SiteKey = _appConfiguration["Recaptcha:SiteKey"],
                SecretKey = _appConfiguration["Recaptcha:SecretKey"]
            });

            //Hangfire (Enable to use Hangfire instead of default job manager)
            //services.AddHangfire(config =>
            //{
            //    config.UseSqlServerStorage(_appConfiguration.GetConMyCompanytionString("Default"));
            //});

            //Configure Abp and Dependency Injection
            return services.AddAbp<MyProjectWebHostModule>(options =>
            {
                //Configure Log4Net logging
                options.IocManager.IocContainer.AddFacility<LoggingFacility>(
                    f => f.UseAbpLog4Net().WithConfig("log4net.config")
                );
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //Initializes ABP framework.
            app.UseAbp(options =>
            {
                options.UseAbpRequestLocalization = false; //used below: UseAbpRequestLocalization
            });

            app.UseCors(DefaultCorsPolicyName); //Enable CORS!

            app.UseAuthentication();
            app.UseJwtTokenMiddleware();

            if (bool.Parse(_appConfiguration["IdentityServer:IsEnabled"]))
            {
                app.UseJwtTokenMiddleware("IdentityBearer");
                app.UseIdentityServer();
            }

            app.UseStaticFiles();

            if (DatabaseCheckHelper.Exist(_appConfiguration["ConMyCompanytionStrings:Default"]))
            {
                app.UseAbpRequestLocalization();
            }

#if FEATURE_SIGNALR
            //Integrate to OWIN
            app.UseAppBuilder(ConfigureOwinServices);
#endif

            //Hangfire dashboard & server (Enable to use Hangfire instead of default job manager)
            //app.UseHangfireDashboard("/hangfire", new DashboardOptions
            //{
            //    Authorization = new[] { new AbpHangfireAuthorizationFilter(AppPermissions.Pages_Administration_HangfireDashboard)  }
            //});
            //app.UseHangfireServer();

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

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

            // Enable middleware to serve generated Swagger as a JSON endpoint
            app.UseSwagger();
            // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "MyProject API V1");
            }); //URL: /swagger
        }

#if FEATURE_SIGNALR
        private static void ConfigureOwinServices(IAppBuilder app)
        {
            GlobalHost.DependencyResolver.Register(typeof(IAssemblyLocator), () => new SignalRAssemblyLocator());
            app.Properties["host.AppName"] = "MyProject";

            app.UseAbp();
            app.UseAesDataProtectorProvider();

            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);

                var hubConfiguration = new HubConfiguration
                {
                    EnableJSONP = true
                };

                map.RunSignalR(hubConfiguration);
            });
        }
#endif
    }
}

AuthConfigurer.cs:

using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Runtime.Security;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;

namespace MyCompany.MyProject.Web.Startup
{
    public static class AuthConfigurer
    {
        public static void Configure(IServiceCollection services, IConfiguration configuration)
        {
            var authenticationBuilder = services.AddAuthentication();

            if (bool.Parse(configuration["Authentication:JwtBearer:IsEnabled"]))
            {
                authenticationBuilder.AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        // The signing key must match!
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])),

                        // Validate the JWT Issuer (iss) claim
                        ValidateIssuer = true,
                        ValidIssuer = configuration["Authentication:JwtBearer:Issuer"],

                        // Validate the JWT Audience (aud) claim
                        ValidateAudience = true,
                        ValidAudience = configuration["Authentication:JwtBearer:Audience"],

                        // Validate the token expiry
                        ValidateLifetime = true,

                        // If you want to allow a certain amount of clock drift, set that here
                        ClockSkew = TimeSpan.Zero
                    };

                    options.Events = new JwtBearerEvents
                    {
                        OnMessageReceived = QueryStringTokenResolver
                    };
                });
            }

            if (bool.Parse(configuration["IdentityServer:IsEnabled"]))
            {
                authenticationBuilder.AddIdentityServerAuthentication("IdentityBearer", options =>
                {
                    options.Authority = configuration["App:ServerRootAddress"];
                    options.RequireHttpsMetadata = false;
                });
            }
        }

        /* This method is needed to authorize SignalR javascript client.
         * SignalR can not send authorization header. So, we are getting it from query string as an encrypted text. */
        private static Task QueryStringTokenResolver(MessageReceivedContext context)
        {
            if (!context.HttpContext.Request.Path.HasValue ||
                !context.HttpContext.Request.Path.Value.StartsWith("/signalr"))
            {
                //We are just looking for signalr clients
                return Task.CompletedTask;
            }

            var qsAuthToken = context.HttpContext.Request.Query["enc_auth_token"].FirstOrDefault();
            if (qsAuthToken == null)
            {
                //Cookie value does not matches to querystring value
                return Task.CompletedTask;
            }

            //Set auth token from cookie
            context.Token = SimpleStringCipher.Instance.Decrypt(qsAuthToken, AppConsts.DefaultPassPhrase);
            return Task.CompletedTask;
        }
    }
}

ABP版本:3.2.5 项目版本:5.0.4

1 个答案:

答案 0 :(得分:0)

我通过对appsettings.json文件进行微小更改来解决问题。 IdentityServer已启用appsettings.json,我们必须将其停用。

"IdentityServer": {
"IsEnabled": "false",