4

I am building an intranet application using Visual Studio 2019 Community for creating a .NET Core Web Api (with .NET Core 2.2) and Visual Studio Code for creating Angular front-end (@angular/cdk 7.1.0, @angular/cli 7.0.6, @angular/material 7.1.0). Since it is an intranet application, I want to implement windows authentication so that users do not have to enter their credentials again. I state that I have already tried this and other forums without success, I am not very familiar with these technologies so I need help to solve some problems I encountered, I probably didn't understand how CORS works.

I tried to call my web API also from postman (with the default settings = "Authorization: Inherit auth from parent"...) but with the same result. I have installed Microsoft.AspNetCore.Cors from NuGet and implemented the following code.

On the Web API side I have this code.

launchSettings.json

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:62148",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebApiWinAuth": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
                services.AddCors(c =>
    {
        c.AddPolicy("AllowOrigin",
            options => options
                    .AllowAnyOrigin()
                    //.WithOrigins("http://localhost:4200")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                );
    });

    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
        .AddJsonOptions(options =>
        {
            var resolver = options.SerializerSettings.ContractResolver;
            if (resolver != null)
                (resolver as DefaultContractResolver).NamingStrategy = null;
        });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors(options => options
        .AllowAnyOrigin()
        //.WithOrigins("http://localhost:4200")
        .AllowAnyMethod()
        .AllowAnyHeader()
   );

    app.UseMvc();
}

ValuesController.cs

[Route("api/[controller]")]
[ApiController]
[Authorize]
[EnableCors("AllowOrigin")]
public class ValuesController : ControllerBase
{
    // GET api/values
    [EnableCors("AllowOrigin")]
    [HttpGet]
    [Authorize]
    public ActionResult<string> Get()
    {
        var userId = HttpContext.User.Identity.Name;
        return userId;
    }
}

On the angular side I have this code.

identity.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class IdentityService {

  constructor(private http:HttpClient) { }

  getCurrentUser() {

    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      }),
      withCredentials: true
     };
    return this.http.get('http://localhost:62148/api/values', httpOptions)
      .toPromise();
  }
}

app.component.ts

export class AppComponent implements OnInit {
  title = 'Angular WinAuth';
  currentUser:string;

  constructor(private service: IdentityService) { }

  ngOnInit() {
    this.service.getCurrentUser().then(res => this.currentUser = res as string);
  }
}

The response I keep getting is "HTTP Error 401.2 - Unauthorized" from both Postman and the angular application.

Where am I doing wrong ? How should I implement the call from angular to the Web Api?

Let me know if I have to post another code please. Thanks in advance

marcofo23
  • 43
  • 1
  • 1
  • 5

2 Answers2

1

I'm new to .Net Core and am encountering a similar issue when using Windows authentication. I've checked numerous posts but none have provided a solution. With MVC 4 or 5 changes to applicationhost.config resolved similar issues.

I found that if I change my port the application will launch in debug mode and Window Authentication will work fine. The second time I launch the application I'll get 401.1 or 401.2 errors.

I've since switched to using Chrome for development and it seems to work fine. It is not ideal because our corporate user base in on IE or Edge.

1

It works when I set anonymousAuthentication:true in launchSettings.json:

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

And from the introduction of Windows Authentication and CORS in asp.net core, I change the startup.cs like below:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(IISDefaults.AuthenticationScheme);//Add this line
        services.AddCors(c =>
        {
            c.AddPolicy("AllowOrigin",
                options => options
                        //.AllowAnyOrigin()
                        .WithOrigins("http://localhost:4200")
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials()//Add this line
                    );
        });

        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(options =>
            {
                var resolver = options.SerializerSettings.ContractResolver;
                if (resolver != null)
                    (resolver as DefaultContractResolver).NamingStrategy = null;
            });

    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseCors("AllowOrigin");

        app.UseMvc();
    }
}
Ryan
  • 19,118
  • 10
  • 37
  • 53
  • Your code is fine, but due to an "Access-Control-Allow-Origin" error I had to integrate your solution with this one: https://stackoverflow.com/questions/42199757/enable-options-header-for-cors-on-net-core-web-api Thanks! – marcofo23 Aug 01 '19 at 10:24