Can’t Use HttpHeaders and WithCredentials Option Together

  angular, angular-httpclient

I have a .net5 WebApi which requires the credentials to be sent from my Angular application. Everything is ok when I use an HttpInterceptor to specify that all my requests will include the credentials in every call, but if I put withCredentials option together with any HtpHeaders the requests don’t pass the CORS validation.

Here is how my interceptor look like (which work fine):

@Injectable({ providedIn: 'root' })
export class HttpInterceptService implements HttpInterceptor {

  constructor() { }

  public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request.clone({
      withCredentials: true
    }));
  }
}

But if the call is made as below, the CORS validation don’t pass:

public apiCall(): Observable<any> {
  return this.httpClient.get(API_URL, {
    withCredentials: true,
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      Authorization: 'my-auth-token'
    })
  });
}

CORS error (when I use withCredentials together with headers):

CORS error

But if I remove the headers, everything work fine:

public apiCall(): Observable<any> {
  return this.httpClient.get(API_URL, {
    withCredentials: true
  });
}

Source: Angular Questions

One Reply to “Can’t Use HttpHeaders and WithCredentials Option Together”

  • Make sure that your WebApi Startup.cs includes the appropriate header. Without it, CORS will fail.
    For example:

    var hosts = Configuration.GetSection("Cors:AllowedOrigins").Get<List<string>>();

    // Dependency Injection
    // services.AddCors();
    services.AddCors(options =>
    {
    options.AddPolicy("MyAllowSubdomainPolicy",
    builder =>
    {
    builder
    .SetIsOriginAllowedToAllowWildcardSubdomains()
    .WithOrigins(hosts.ToArray())
    .WithHeaders("Authorization")
    // .AllowAnyHeader()
    .AllowAnyMethod();
    });
    });

Leave a Reply to Terry Davis Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.