Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net Core allow custom headers with CORS (with axios on client side)

I have an single app (in Vuejs) + axios on client side and Asp.net Core Web Api server side. I have add a jwt token auth. I have configured my server to add a custom header when the token is expired. (I had "Token-Expired" header in the response).

The header "token-expired" was not present in error.response.headers object from axios interceptor ... (Note: It is frustrating because the header is present on Postman but not with axios).

Edit: This issue on github seems similary to my case https://github.com/axios/axios/issues/606

like image 213
rdhainaut Avatar asked Sep 14 '25 23:09

rdhainaut


1 Answers

By default, the browser doesn't expose all of the response headers to the app. For more information, see W3C Cross-Origin Resource Sharing (Terminology): Simple Response Header.

The response headers that are available by default are:

  • Cache-Control
  • Content-Language
  • Content-Type
  • Expires Last-Modified
  • Pragma

Source: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2#set-the-exposed-response-headers

More general info: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2

To make other headers available to the app, call WithExposedHeaders method in the Configure from startup.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   // ...

   app.UseCors(builder =>
   {
      builder.WithOrigins("http://localhost:8080");
      builder.AllowAnyHeader();
      builder.WithExposedHeaders("Token-Expired");
      builder.AllowAnyMethod();
      builder.AllowCredentials();
      builder.Build();
   });
}

Note: You must set an specific origin (and not add AllowAnyOrigin() method). Indeed, The CORS specification also states that setting origins to "*" (all origins) is invalid if the Access-Control-Allow-Credentials header is present.

Et voilà :)

like image 138
rdhainaut Avatar answered Sep 17 '25 00:09

rdhainaut