0

This is not a duplication post,I know may be a part of the title asked many times in stackoverflow community, I checked all posts, and answers, but I think my problem and technologies which I used are different.

First of all I should mention ASP.NET Core WEB/API is my back-end-app and Reactjs is my front Application.

I read about CORS and I found out I must enable CORS on ASP.NET App and put 'Access-Control-Allow-Origin':'*' on my request's header, but I still have the below error while I call an api:

Actually we have two URL, one is the normal and the other one is the vanity url, vanity url is basically used as for redirection purpose. So when we use vanity url as both for api and front end it works but when the frontend and api are different we are getting CORS error, although we have added cors policy on server side code still we are getting the error when domains are different.

Tried almost every solution present on stackoverflow.

Below is the error i am getting

Access to fetch at 'https://abc123.com/api/home/getLoggedInUser/' from origin 'https://xyz123.com' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled

This is my Program.cs code related to CORS:

  builder.Services.AddCors(options =>

   {

  options.AddPolicy(      "CorsPolicy",

     builder => builder.WithOrigins("http://localhost:3000"
     , "https://abc123.COM"
     , "https://abc123.com"
     , "https://abc123com"
     , "https://abc123.com"
     , "https://xyz123.com"
     , "https://xyz123.com"
     , "https://xyz123.com"
     , "https://xyz123.com")
     .AllowAnyMethod()
     .AllowAnyHeader()
     .AllowCredentials());
    });
    builder.Services.AddHttpContextAccessor();
    builder.Services.AddControllers();
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    builder.Services.AddAuthentication(IISDefaults.AuthenticationScheme);
    var app = builder.Build();
    app.UseCors("CorsPolicy");
    // Configure the HTTP request pipeline.
    if (app.Environment.IsEnvironment("Local"))    
    {
       app.UseSwagger();
       app.UseSwaggerUI();
    }

    app.UseHttpsRedirection();
    app.UseDefaultFiles();
    app.UseAuthentication();
    app.UseAuthorization();   
    app.MapControllers();
    app.Run();

This is my React code

     useEffect(() => {
        fetch(url + "home/getLoggedInUser/"+window.TestingUser, {
           credentials: "include",
           mode: 'cors',
           headers: {
              "accepts": "application/json"
               }
          })
          .then(res => res.json())
          .then(result =>console.log(result)) 
 
       }, [])

Thanks

===================

Op mentioned in the comment that the CORS issue didn't happen in local side, only happened after deploy to IIS in AWS server.

Tiny Wang
  • 10,423
  • 1
  • 11
  • 29
ayush mishra
  • 103
  • 2
  • 8
  • Are you sure you want a method called "getLoggedInUser" that sends credentials to allow CORS? (seems like an XSS/CSRF vector)... For your problem, according to this link, you can't set cors headers to wildcard when credentials are included: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#sending_a_request_with_credentials_included – pcalkins Mar 13 '23 at 21:41
  • you may also want to use "Accept" as that header name... not sure Fetch api allows "accepts". – pcalkins Mar 13 '23 at 22:27
  • not sure why the cors policy doesn't work for you, but following the document, `app.UseCors("CorsPolicy");` should put behind `app.UseHttpsRedirection();`. by the way, could you pls check if you are running the api project with IIS express in VS with `anonymousAuthentication` in lanuchSetting set to false? if it's false, maybe we can change to true. In the meantime, cors issue is reported by the browser itself, so we can set a proxy for the react app to avoid this error as a [workaround](https://stackoverflow.com/a/73459204). – Tiny Wang Mar 14 '23 at 07:40
  • @TinyWang Will check by putting app.UseCors("CorsPolicy"); behind app.UseHttpsRedirection(). anonymousAuthentication is true. Didn't get the error on local, it give me the error after deployment – ayush mishra Mar 14 '23 at 08:15
  • hmmm, ok then where you deployed? just like you said, the cors policy worked well in the local side, so it looks like some other settings caused the issue. like you know, for example when we publish the app to azure web app we can also set cors enabled in azure portal for this app. – Tiny Wang Mar 14 '23 at 08:28
  • It is deployed on IIS of AWS server – ayush mishra Mar 14 '23 at 08:51
  • for iis we may check [this setting](https://learn.microsoft.com/en-us/iis/extensions/cors-module/cors-module-configuration-reference#cors-configuration). – Tiny Wang Mar 15 '23 at 02:37
  • Thanx everyone for your comments...The issue generated as Port 80 is not open on server where the application is deployed, after fixing application runs smoothly – ayush mishra Apr 06 '23 at 10:28

1 Answers1

0

Try enabling Cors policy to work with everything. In your Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
...
app.UseCors(x => x
                .AllowAnyMethod()
                .AllowAnyHeader()
                .SetIsOriginAllowed(origin => true) // allow any origin
                .AllowCredentials());
Ezra
  • 49
  • 4