Madhu
Madhu

Reputation: 439

Angular 6 - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header

I'm getting CORS error when calling a POST or DELETE Core API from my Angular application.

My Core Web API's are configured with Windows Authentication. And [Authorize] attribute is at controller level. Whenever I pass a GET request from Angular, the request is getting authorized and I'm getting the response back.

When sending a POST request from Angular to Core API,

1) If I pass data as FormData from Angular service to Core API, it is working fine.

2) If I pass data as Model from Angular service to Core API, I'm getting the below error

Failed to load http://localhost:63854/api/sampleController/1: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:52871' is therefore not allowed access

Here is Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options => options.AddPolicy("AllowAll",
        builder => builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials()));

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("AllowAll");

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseMvc();
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "APIs"));
    app.UseMvcWithDefaultRoute();
}

Core API action method:

[Authorize]
[Produces("application/json")]
[Route("api/someRoute")]

public class someController : Controller
{
    [HttpPost]
    [Route("update")]
    public async Task<HttpResponseMessage> UpdateAccessType([FromBody] TestModel modalObj)
    {
         //code..
    }

    [HttpDelete("{id}")]
    public async Task<HttpResponseMessage> DeleteAccessType(string id)
    {
        //code..
    }
}

Angular Service: accessType is constructed in component, and passed as object to angular service.

updateAccessType(accessType) {
    return this.http.post(this.apiUrl + "api/someController/update", accessType);
}

deleteAccessType(accessLookupId: string) {
    return this.http.delete(this.apiUrl + "api/someController/" + accessLookupId);
}

Complete error message (But this is happening only when passing data as modal, not happening when passing data as FormData) - Both DELETE and POST requests gives the same exception.

HTTP Error 401.2 - Unauthorized - You are not authorized to view this page due to invalid authentication headers

I like to pass model from Angular to Core API instead of FormData.

Upvotes: 3

Views: 6064

Answers (2)

Peter V&#246;geli
Peter V&#246;geli

Reputation: 51

If you want to use Cors, in combination with Windows Authentication, you have to enable also the "Anonymous Authentication". Tried all other solutions, but with no success.

In Angular, I had to implement HttpInterceptor to put it to work.

import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';

@Injectable()
export class WithCredentialsInterceptor implements HttpInterceptor {
  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    request = request.clone({
      withCredentials: true
    });

    return next.handle(request);
  }

Upvotes: 1

User3250
User3250

Reputation: 3421

Try using below in Configure method instead:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
}

Upvotes: 1

Related Questions