When calling my REST Service in Angular, there are no response headers.
Login method in Angular
The headers in an HttpResponse object are lazy-loaded, so headers
will appear to be empty until you force the values to be loaded. Try calling response.headers.keys()
to see all available header names. By the way, this also forces all values to be loaded into the map response.headers.headers
.
Be sure to use headers.get('my-header-name')
if you only need to access one particular header value.
By default CORS responses only expose these 6 headers :
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
To allow the scripts to access other headers sent by the sever, the server needs to send the Access-Control-Expose-Headers Header.
The Access-Control-Expose-Headers response header indicates which headers can be exposed as part of the response by listing their names.
eg: Access-Control-Expose-Headers: Authorization, X-Foobar
You can tweak your web.xml
file including this to allow the Authorization
header to be accessed from the script that made the XHR:
<init-param>
<param-name>cors.exposedHeaders</param-name>
<param-value>Authorization</param-value>
<init-param>
I used the following solution to allow my custom header in Owin self-hosted web api
using Owin;
using Microsoft.Owin.Cors;
using System.Threading.Tasks;
using System.Web.Cors;
namespace App.Web.App_Start
{
public static class CorsConfig
{
public static void Configure(IAppBuilder app)
{
var allowedOrigins = "comma,separated,list,of,origins";
var corsPolicy = new CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true,
AllowAnyOrigin = false,
SupportsCredentials = true
};
corsPolicy.ExposedHeaders.Add("Custom-Header");
foreach (string origin in allowedOrigins.Split(','))
corsPolicy.Origins.Add(origin);
app.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(corsPolicy)
}
});
}
}
}
I call the method like this CorsConfig.Configure(app); // app is Owin.IAppBuilder