Sunday 30 June 2019

Browser not sending cookies cross-origin cross domain with CORS enabled

I have a .net core webapi project set up to accept cross origin requests like so

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseCors(opts => opts
        .WithOrigins("https://fiddle.jshell.net")
        .AllowCredentials()
        .AllowAnyMethod()
        .AllowAnyHeader());

    app.UseHttpsRedirection();
    app.UseMvc();
}

This has a values controller with a GET method like so

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return Ok("cookies: " + string.Join(", ", HttpContext.Request.Cookies.Select(x => x.Key)));
    }
}

Now I am trying to send a fetch request from the browser like so

fetch('https://api.domain.com/api/values', { 
    headers: 
  { 
    'Content-Type': 'application/json' 
    }, 
    credentials: 'include', 
    mode: 'cors'
})
.then(function(resp){ 
    resp.text().then(function(data) { 
        console.log(data); 
  }) 
})
.catch(function(err){ 
    console.log(err) 
});

But this doesn't send the cookies from the page to the api. What am I missing here? I have tried all the solutions I could find about this including turning off third party cookies

Update I should mention that cookies from the same domain are being sent but not from a sub-domain. For example if the backend url is api.domain.com and then UI is at ui.domain.com the any cookies that belong to domain.com are sent along but those belonging to ui.domain.com are not.



from Browser not sending cookies cross-origin cross domain with CORS enabled

No comments:

Post a Comment