【问题标题】:How to include Access-Control-Allow-Credentials in ASP .Net Core app?如何在 ASP .Net Core 应用程序中包含访问控制允许凭据?
【发布时间】:2023-01-26 04:22:34
【问题描述】:

是否有明确的“Access-Control-Allow-Credentials”属性明确允许凭据随请求发送到特定客户端站点?

我尝试了以下

var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.WithOrigins("http://my-account-name.github.io",
                                              "http://my-account-name.github.io/My-repository",
                                              "https://my-account-name.github.io",
                                              "https://my-account-name.github.io/My-repository");
                      });
});
...

app.UseCors(MyAllowSpecificOrigins);

Not working solution source

对于那些包含凭据标头和/或授权 cookie 的请求,我在 Chrome 控制台中得到了“CORS”策略限制。其他请求(不包括凭据)通过cors 获取()来自 JS。

【问题讨论】:

  • 我注意到你提到了credential headers and authorize cookies,也许this link 会帮助你。
  • @Chen,是的,这很有帮助!我还发现有一个 Cookie.SameSite = SameSiteMode.None; 配置属性可以让 cookie 不被浏览器的 CORS 策略(松散/严格而不是无)阻止。

标签: c# asp.net-core session-cookies credentials asp.net-authorization


【解决方案1】:

CORS Cookie Authorization 的完整解决方案是 SameSite = None; cookie 策略(告诉浏览器来自你的服务器)

// Controller.cs
    [EnableCors("_allowSpecific")] // !!!
    public class YourController : Controller
// ...
// Startup.cs

        string MyAllowSpecificOrigins = "_allowSpecific";

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSession(options =>
            {
                options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None; // !!!
            });
            services.AddCors(options => {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                    policy => { policy.WithOrigins( "http://your-domain.your-site.com", "https://your-domain.your-site.io", "http://your-domain.your-site.io"
#if DEBUG // Use this for debugging CORS in NPM localhost
                        , "http://localhost:8081", "https://localhost:8081", "http://127.0.0.1:8081", "http://192.168.1.64:8081"
#endif
                    ).AllowAnyHeader().AllowAnyMethod().AllowCredentials(); 
                });
            });
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true; // !!!
                options.MinimumSameSitePolicy = SameSiteMode.None; // !!!
            });

            // ADD your services, DbContexts, Identity, Configure<IdentityOptions>, AddDefaultIdentity<IdentityUser>, 
            // AddRoles<IdentityRole>, AddEntityFrameworkStores<ApplicationDbContext>
            // ConfigureApplicationCookie, AddDatabaseDeveloperPageExceptionFilter, AddSingleton<IHttpContextAccessor>, AddRazorPages, AddControllersWithViews
            // AddLogging, 

            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.SameSite = SameSiteMode.None; // !!!
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(10000);
                options.SlidingExpiration = true;
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, IWebHostEnvironment env, Microsoft.Extensions.Hosting.IHostApplicationLifetime appLifetime)
        {
            // if (env.IsDevelopment()) ...
            app.UseCookiePolicy(new CookiePolicyOptions
            {
                MinimumSameSitePolicy = SameSiteMode.None // !!!
            });
            // app.UseRouting(); ...

            app.UseCors(MyAllowSpecificOrigins); // ? 1) not sure whether you need to use both, but it works
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseCors(MyAllowSpecificOrigins); // ? 2) not sure if you need to use both, but it works

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}") .RequireCors(MyAllowSpecificOrigins); // !!!
                endpoints.MapRazorPages() .RequireCors(MyAllowSpecificOrigins); // !!!
                endpoints.MapControllers() .RequireCors(MyAllowSpecificOrigins); // !!!
            });
        }

//...

【讨论】:

    猜你喜欢
    • 2019-03-22
    • 2023-03-09
    • 2019-02-01
    • 1970-01-01
    • 2015-04-28
    • 2017-03-03
    • 1970-01-01
    • 2014-04-16
    • 2015-08-24
    相关资源
    最近更新 更多