0

Im building some angular app that will use .net core webapi. it is working fine when i use enable anonymous authentication, but fails with windows authentication ;/ no mather if hosted in iis express or in full iis on windows server. also

i added cors policy to webapi , i added withCredentials : true to angular http call , added .AllowCredentials(); to api cors config still error ocurrs

the api call is fine when made from postman with NTLM authentication enabled and added my domain / user / pass into it

web api have:

   public void ConfigureServices(IServiceCollection services)
    {
        string[] HostOrigins = new string[] { "http://localhost:4200", "https://localhost:4200" };

        services.AddCors(options =>   
        {
            options.AddPolicy("CorsPolicy", builder =>
            {
                builder.WithOrigins(HostOrigins)
                        .AllowAnyHeader().AllowAnyMethod().AllowCredentials();
            });
        });
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);     
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {        
            app.UseHsts();
        }
        app.UseCors("CorsPolicy");
        app.UseHttpsRedirection();
        app.UseMvc();
    }
}

in angular service to do post request:

Post(endpoint: string, PostData: any, callbackF: ((data) => void) , errorF?: ((error) => void) ) 
{
return this.http.post(endpoint, PostData, { withCredentials : true })
  .subscribe(
    (data) => callbackF(data),
    (error) => {
      if (errorF) { errorF(error); }
      else {
      console.log('unCatch error:' + (JSON.stringify(error)));
      }
    }
);

and actual service call in angular component

  this.DataService.Post('http://localhost:51500/sp/ApiTest',
  {str1: 'asd', int1: '1', bit: 'false'},
  (data: any) => {                
                  console.log(JSON.stringify(data));
                 });   

it fails with

  unCatch error:{"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"http://localhost:51500/sp/ApiTest","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost:51500/sp/ApiTest: 0 Unknown Error","error":{}}
 HTTP401: ...
 (XHR)OPTIONS — http://localhost:51500/sp/ApiTest

in firefox it also claims that it is same origin policy error but if it would be that - it should also fail when using anonymous auth? i known that firefox like to claim that 'other error' = 'cors error' ;)

please advaice if someone had problem like this

best regards !

edit here is what i recive in postman - it means that it works but i see no cors header ? is it ok or it should be there ? enter image description here

d00lar
  • 301
  • 1
  • 9
  • Can you show me your program.cs? – TheCondorIV Aug 08 '19 at 12:53
  • How do you use the address localhost:4200? is it the address your frontend is running on? – Martin Staufcik Aug 08 '19 at 13:01
  • yes it is ng serve default when building angular app and it is the host from witch im trying to make this api call – d00lar Aug 08 '19 at 13:06
  • You need to allow anonymous options requests. See [this](https://stackoverflow.com/questions/27414487/webapi-cors-with-windows-authentication-allow-anonymous-options-request) post. – Martin Staufcik Aug 08 '19 at 13:07
  • the program.cs is default not touched by me public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup(); } – d00lar Aug 08 '19 at 13:07
  • https://www.c-sharpcorner.com/article/configure-windows-authentication-in-asp-net-core/ – Adrita Sharma Aug 08 '19 at 13:14
  • hmm i will try but i thing that this article is outdated cause if im able to make this api call from postman. also if i add some GET method for example that return return Ok(_httpContextAccessor.HttpContext.User.Identity.Name) it shows my username in browser so it is supported by this default iis express server nowdays i think? – d00lar Aug 08 '19 at 13:26
  • please see added image - it says kastrel but handles this ntlm authorization fine..? – d00lar Aug 08 '19 at 13:33

1 Answers1

-1

thanks to Martin Staufcik link i managed it to work by

enabled anonymous authentication AND windows authentication at the same time

in api ConfigureServices added

services.AddAuthentication(IISDefaults.AuthenticationScheme);

and in controllers added [Authorize] attribute

and indeed it works it was the same issue - iis returning unauthorized because it canot do options request - options request is made with no authentication provided inside.

thanks all!

d00lar
  • 301
  • 1
  • 9
  • Here is potential cause of this - http handshake with options request ? It have some sense for me - can anyone confirm that this may be the issue ? https://stackoverflow.com/a/10820339/11305308 – d00lar Aug 08 '19 at 15:17
  • The reason this happens is that the CORS request carries no credential information by design. You need to have anonymous access enabled so that the CORS OPTIONS request can get processed. You then need have windows on for your normal app authentication. Here's a great [explanation](https://blogs.msdn.microsoft.com/friis/2017/11/24/putting-it-all-together-cors-tutorial/) – Fran Aug 08 '19 at 15:31
  • Thanks ! All clear now ! I googled a lot but not found that article before ;p – d00lar Aug 08 '19 at 16:41