1

I have recently been tasked with creating the company's internal website with the use of ASP.NET Core 3.0 API and Angular 8.

In order to authorize the users, I have set up the API Project with Windows Authentication and included this in Startup.cs

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(IISDefaults.AuthenticationScheme);

        services.AddCors(options =>
        {
            options.AddPolicy("FrontEndPolicy",
                builder => builder.WithOrigins("http://localhost:4200")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
        });

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));

        AddScopedServices(services);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors("FrontEndPolicy");
        app.UseHttpsRedirection();
        app.UseRouting();

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

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

I tested the Basic API Calls in Postman and it was working all fine, so I set up the CORS, Created Angular project and carried on over there. Created Interceptor that adds credentials to my requests:

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

And then executed simple GET Method(It returns current user):

  getUser() {
return this.http.get
  (environment.apiUrlCoreUserHttp,
    { observe: 'response' });}

This is working just fine and returns desired data(username):

GET Method Test

Happy with result I decided I will test POST method, so again created simple method which should just return message to the Console:

API Project:

    [HttpPost]
    [Route("{siteName}/post")]
    public ActionResult<string> PostForm()
    {
        return User.Identity.Name == null ? $"Posted data as Anonymous user" : $"Posted data as {User.Identity.Name}";
    }

In Angular:

post() {
var body = {};

return this.http.post(environment.apiUrlCoreHttp + "dynamicsites/cheesestore/post", 
body, 
{responseType: 'text'}).subscribe(res => console.log(JSON.stringify(res)));}

However, the response Status Code is 401:

Response Value

POST Headers

I assume given the error that there's an issue with the Preflight request in the response headers. I decided then to test the post method without Authentication turned on and the result was positive and I got required data back in the console:

POST Headers without Auth

I assume the reason why I have the error with auth turned on is lack of the certain response headers in the options preflight request i.e. :

Access-Control-Allow-Headers:content-type Access-Control-Allow-Methods:POST Access-Control-Allow-Origin:http://localhost:4200

which were missing in previous request. I have tried to find a relevant solution but without any luck. Did anyone get an issue with Windows Authentication/CORS scenario? I must admit it's horribly vague because GET works just fine and POST not at all if authentication is turned on when trying to reach the data from the front end side.

Necrophallus
  • 204
  • 2
  • 10
  • If your API project is hosting on IIS server, you can use [IIS CORS module](https://learn.microsoft.com/en-us/iis/extensions/cors-module/cors-module-configuration-reference#cors-preflight-request) that enables web sites to support the CORS protocol, and IIS CORS module provides IIS servers a way to correctly respond to the preflight request. – Fei Han Feb 20 '20 at 02:57
  • Besides, [this SO thread](https://stackoverflow.com/questions/49450854/how-to-authorize-cors-preflight-request-on-iis-with-windows-authentication) discussed a similar issue, you can refer to it. – Fei Han Feb 20 '20 at 02:58

1 Answers1

0

I thought I will share how I managed to sort this out in case someone will need it.

The only thing that needed to be done was within Web API project in StartUp.cs:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
            app.UseCors(option => option.WithOrigins
                ("http://localhost:4200")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());}

This allowed me to post data from my angular application.

Necrophallus
  • 204
  • 2
  • 10