0

I have this problem that driving me nuts ... I got backend API, that has CORS enabled and Windows Authentication, looks like this

launchSettings.json:

"iisSettings": {
   "windowsAuthentication": true,
   "anonymousAuthentication": false,
   ....
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}

And

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

     app.UseRouting();
     app.UseAuthentication();
     app.UseAuthorization();

     app.UseCors(builder => builder
        .AllowAnyOrigin()
        .AllowAnyHeader()
        .AllowAnyMethod());

     app.UseEndpoints(endpoints =>
     {
         endpoints.MapControllers();
      });
}

TokenController.cs

[ApiController]
[Route("[controller]")]
public class TokenController : ControllerBase
{
    private TokenService userService;
    IHttpContextAccessor httpContextAccessor;

    public TokenController(TokenService _userService, 
                           IHttpContextAccessor _httpContextAccessor)
    {
        userService = _userService;
        httpContextAccessor = _httpContextAccessor;
    }

    /// <summary>
    /// Creates token for domain signed user of Unicredit group
    /// </summary>
    /// <returns>Authenticate</returns>
    [HttpGet]
    [Route("")]
    [ProducesResponseType(typeof(string), 200)]
    [ProducesResponseType(typeof(string), 400)]
    [ProducesResponseType(typeof(string), 404)]
    [Produces("application/json")]
    public IActionResult Authenticate()
    {
        string username = httpContextAccessor.HttpContext.User.Identity.Name;
        ... further reading from AD and making JWT token 
    }

React - Authenticate.js (doing simple fetch)

fetch(`${AuthenticationEndpoint}/`)
     .then(response => response.json())
     .then(data => this.onSetResult(data));

So when I call my API with use of Boomerang (Postman alike) and just doing simple GET for https://localhost:{port}/Token/, I get status 200 and my JWT Token back, but once I do fetch from my React application I keep getting error:

Access to fetch at 'https://localhost:44351/Token/' from origin 'http://localhost:3000' has been blocked by CORS policy

I understand not Boomerang nor Postman are restricted by policy and that's reason why they can pass to my API, but how can I let my application access my API?

Veljko89
  • 1,813
  • 3
  • 28
  • 43

1 Answers1

0

FIXED IT

Because I had

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,

My cors were expecting username, which I do need in order to query AD and make JWT token

I had to change fetch, and set credentials to include and change useCors in Startup.cs

fetch(`${AuthenticationEndpoint}/Authenticate`, {
            credentials: "include",
            method: "GET",
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }).then((response) => {
            response.json().then(data => {
                this.onSetResult(data);
            })
 });

And CORS on backend were set like this:

 app.UseCors(builder => builder.WithOrigins("http://localhost:3000")
                               .AllowAnyMethod()
                               .AllowAnyHeader()
                               .AllowCredentials());
Veljko89
  • 1,813
  • 3
  • 28
  • 43