-1

I have a problem when i make httppost and httput (httpget is OK) to an API .net core 3.1 by an Angular 10 front, the error in console application is the famous : Access to XMLHttpRequest at 'http://localhost:23645/api/Toolbar/Search' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

capture

this the code of my front request :

constructor(private Http: HttpClient) {
    this.header =  new HttpHeaders(
      {
        'content-type': 'application/json'
      }
    )

searchToolbar(search: string): Observable<ToolbarSearchResultItem[]> {
    
    return this.Http.post(this.url + '/myController/Search', { "search": search }, { headers: this.header, withCredentials:true}).pipe(tap((response: myTyoe[]) => {
      return response;
    }));

this is my code in Startup.cs :

public void ConfigureServices(IServiceCollection services)
        {
            log.Info("ConfigureServices");
            try
            {
                IConfigurationRoot configurationRoot = builder.Build();

                services.AddCors(opt => opt.AddPolicy("CorsPolicy", c =>
                {
                    c.WithOrigins("http://localhost:4200")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                

            }));
                services.AddAuthorization(options =>
                {
                    options.AddPolicy("AllUsers", policy => policy.RequireAuthenticatedUser());
                });
                
            services.AddControllers();

            services.AddMvc();

            }
            catch (Exception ex)
            {
                log.Error("Error in ConfigureServices" + ex.Message + ex.StackTrace);
            }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    try
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseRouting();

        app.UseCors("CorsPolicy");
        app.UseAuthorization();

in a launchSettings.json i set this :

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:23645",
      "sslPort": 0
    }

and in applicationhost.config:

 <windowsAuthentication enabled="true">
          <providers>
            <add value="Negotiate" />
            <add value="NTLM" />
          </providers>
        </windowsAuthentication>

this is my controller:

 [HttpPost]
        [Route("Search")]
       [EnableCors("CorsPolicy")]
        public IList<ToolbarSearchResultItem> Search(ToolbarSearch search)
        {
//my code
}

this is the detailled message in the console :Request URL: http://localhost:23645/api/Toolbar/Search Request Method: OPTIONS Status Code: 401 Unauthorized Remote Address: [::1]:23645 Referrer Policy: strict-origin-when-cross-origin Cache-Control: private Content-Length: 6284 Content-Type: text/html; charset=utf-8 Date: Tue, 02 Mar 2021 15:52:05 GMT Server: Microsoft-IIS/10.0 WWW-Authenticate: Negotiate WWW-Authenticate: NTLM X-Powered-By: ASP.NET Accept: / Accept-Encoding: gzip, deflate, br Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7 Access-Control-Request-Headers: content-type Access-Control-Request-Method: POST Connection: keep-alive Host: localhost:23645 Origin: http://localhost:4200 Referer: http://localhost:4200/ Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-site

this is my web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath=".\MYEXE.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

I think that it is not really a CORS block problem but a configuration problem or other, it is very similar to this question : Trouble with CORS Policy and .NET Core 3.1 but I used a profiler and I don't have an SQL Problem

jps
  • 20,041
  • 15
  • 75
  • 79
HachDotNet
  • 21
  • 1
  • 7
  • You have to know that is anything happened before the CORS middleware (for example if your application crash during the authorization middleware) the produced response will not have CORS header so it will appear as a CORS issue from the browser point of view. You should looked the log generated by ASP.NET (probably in the output window). If you remove your "EnableCors" attribute, is the action correctly reached ? – Arcord Mar 02 '21 at 15:04
  • in the output window i don't have errors, I tried to remove the "EnableCors" attribute and I have the same error. – HachDotNet Mar 02 '21 at 15:21
  • "ConnectionStrings": { "DefaultConnection": "data source=MyServer;initial catalog=DB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework;" , "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } },"AllowedHosts": "*" – HachDotNet Mar 02 '21 at 15:43
  • From angular you are sending request on http://localhost:23645 but in cors you are using http://localhost:4200 . you need to use same urls – NAS Mar 02 '21 at 15:45
  • localhost:4200 is angular url and localhost:23645 is backend url and Httpget requests are OK – HachDotNet Mar 02 '21 at 15:47
  • It works when i set allwoAnomymous to true in launchsettings but i need to log the user login that's why i should set it to false. I tried to decorate the action with AllowAnonymous but it doesn't work – HachDotNet Mar 02 '21 at 16:18
  • Is the CORS middleware before the authorization middleware? Preflight request are never authenticated so it can cause some issue if the authorization middleware is before. – Arcord Mar 02 '21 at 16:45
  • I set services.AddAuthentication(IISDefaults.AuthenticationScheme) before CORS middleware and it didn't work – HachDotNet Mar 02 '21 at 16:52

2 Answers2

1

Remove from your startup Cors config

     .AllowCredentials();

and remove from the controller actions

 [EnableCors("CorsPolicy")]

But you still have have Status Code: 401. It has nothing to do with Cors. It is only about authorization. Just comment all authorization code to test CORS. After this you can start with authorization.

Serge
  • 40,935
  • 4
  • 18
  • 45
0

Access to XMLHttpRequest at 'http://localhost:23645/api/Toolbar/Search' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Please note that a CORS preflight request (using the HTTP OPTIONS method) is used to check whether the CORS protocol is understood and a server is aware using specific methods and headers. And the HTTP OPTIONS requests are always anonymous, you enabled Windows Authentication and disabled anonymous access, which would cause server not correctly respond to the preflight request.

To run your app(s) on local for testing purpose with CORS, to fix this issue, you can try to enable anonymous authentification to allow anonymous access.

Besides, if you would host your app(s) on IIS server, to fix this issue, you can install IIS CORS module and configure CORS for the app.

Fei Han
  • 26,415
  • 1
  • 30
  • 41
  • I agree with Frei Hand And Sergey, I activated Anonymous requests and it works ! To get user infos (that's why i activated only windows authentication before), i decorated actions by Authorize Attribute and I added this in ConfigureServices : services.AddAuthentication(IISDefaults.AuthenticationScheme); and I removed this : services.AddAuthorization(options => { options.AddPolicy("AllUsers", policy => policy.RequireAuthenticatedUser()); }); – HachDotNet Mar 03 '21 at 10:42