无法在asp.net Core中为身份服务器4启用CORS [英] Not able to enable CORS for identity server 4 in asp.net core

查看:184
本文介绍了无法在asp.net Core中为身份服务器4启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我为我的点网核心API添加了CORS策略,但是以某种方式,这些CORS策略不适用于身份服务器4端点. 我使用以下api尝试注册用户:

Ok, I have added CORS policy for my dot net core APIs but somehow these CORS policies are not working for identity server 4 endpoints. I have following api where I try to register a user:

    [EnableCors("AllowAllCorsPolicy")]
    [Route("api/User")]
    public class UserController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private IUserServices _userService;
        public UserController(UserManager<ApplicationUser> userManager, IUserServices userService)
        {
            _userManager = userManager;
            _userService = userService;
        }

        [HttpPost]
        public async Task<int> Post([FromBody]User userInfo)
        {
            var user = new ApplicationUser{  UserName = userInfo.Name, Email = userInfo.Email,
                UserTypeId = Constant.User, CustomerId = userInfo.CustomerId };

            //Follwing 3 lines give CORS issue.
            await _userManager.AddToRoleAsync(user, Constant.User);
            var userClaim = new Claim(Constant.User, user.Email.ToString(), ClaimValueTypes.Integer);
            await _userManager.AddClaimAsync(user, userClaim);

            // var userObj = _userService.AddNewUser(userInfo);
        }

现在,如果我使用上述身份服务器方法( AddToRoleAsync() AddClaimAsync()),我的客户端(在不同服务器上运行的角度应用程序)会出现CORS错误

Now if I use above identity server methods (AddToRoleAsync() and AddClaimAsync()) I get CORS error in my client (angular app running on different server)

但是,如果我使用自定义方法注册用户,则不会收到CORS错误:

However if I use my custom method to register the user, I don't get CORS error:

            //Don't get CORS error when commented below
            //await _userManager.AddToRoleAsync(user, Constant.User);
            //var userClaim = new Claim(Constant.User, user.Email.ToString(), ClaimValueTypes.Integer);
            //await _userManager.AddClaimAsync(user, userClaim);

            //use custom method
            var userObj = _userService.AddNewUser(userInfo);

要为asp.net,startup.cs启用CORS,我正在做

To enable CORS for asp.net, startup.cs I am doing:

    public void ConfigureServices(IServiceCollection services)
            {
              services.AddCors(options =>
             {
                options.AddPolicy("AllowAllCorsPolicy",
                    builder => builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
            });
            services.AddMvc();
          }


public void Configure(IApplicationBuilder app, IHostingEnvironment env,  IServiceProvider serviceProvider)
        {
            app.UseCors("AllowAllCorsPolicy");
        }

我什至尝试在startup.cs中手动添加CORS标头,但没有运气:

I even tried to add the CORS headers manually in startup.cs, but no luck:

public void Configure(IApplicationBuilder app, IHostingEnvironment env,  IServiceProvider serviceProvider)
        {
            app.Use(async (context, next) =>
        {
            if (context.Request.Method == "OPTIONS")
                context.Response.StatusCode = (int)HttpStatusCode.OK;

            var headers = context.Response.Headers;
            if (headers.ContainsKey("Access-Control-Allow-Origin"))
            {
                headers["Access-Control-Allow-Origin"] = string.Join(",", context.Request.Headers["Referer"].Select(x => x.Substring(0, x.Length - 1)));
            }
            else
            {
                context.Response.Headers.Append("Access-Control-Allow-Origin", string.Join(",", context.Request.Headers["Referer"].Select(x => x.Substring(0, x.Length - 1))));
            }
            if (headers.ContainsKey("Access-Control-Allow-Headers"))
            {
                headers["Access-Control-Allow-Headers"] = "Origin, Content-Type, Accept, Client, Authorization, X-Auth-Token, X-Requested-With";
            }
            else
            {
                context.Response.Headers.Append("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Client, Authorization, X-Auth-Token, X-Requested-With");
            }
            if (headers.ContainsKey("Access-Control-Allow-Methods"))
            {
                headers["Access-Control-Allow-Credentials"] = "GET, POST, PATCH, PUT, DELETE, OPTIONS";
            }
            else
            {
                context.Response.Headers.Append("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
            }
            if (headers.ContainsKey("Access-Control-Allow-Credentials"))
            {
                headers["Access-Control-Allow-Credentials"] = "true";
            }
            else
            {
                context.Response.Headers.Append("Access-Control-Allow-Credentials", "true");
            }
            context.Response.Headers.Append("Access-Control-Expose-Headers", "X-Auth-Token");
            context.Response.Headers.Append("Vary", "Origin");
            await next();
        });
        }

我看到了此文档(针对CORS)以及此CORS 文档,但数量不多有帮助的.

I saw this documentation for identityserver Options for CORS and also this CORS documentation but not much helpful.

推荐答案

这适用于服务器的较新版本.

This works for the newer version of the server.

    services.AddSingleton<ICorsPolicyService>((container) => {
        var logger = container.GetRequiredService<ILogger<DefaultCorsPolicyService>>();
        return new DefaultCorsPolicyService(logger)
        {
            AllowAll = true
        };
    });

在此讨论中有更多详细信息,这要归功于原始作者

more details here at this discussion, with credit to the original author

https://github.com/IdentityServer/IdentityServer4/issues/4685

这篇关于无法在asp.net Core中为身份服务器4启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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