This article shows you how to set up an Angular application with .Net Core Web API using Windows Authentication, along with the common pitfall that are time consuming to troubleshoot.
You can download the code or see the latest code at GitHub. This project was done using the Starter Project HERE as the starting point.
The first thing to do is to enable Windows Authentication for .Net Core Web API. You can run the API under IIS Express first to make sure everything is ok, then publish to a location to be hosted by IIS.
Running API Under IIS Express
Running the API under IIS Express is the easiest way to test your setup. First add the code below to Startup.ConfigureServices method to force Windows Authentication on the API. Without the code below the API will not be able to accept Http Post and Put request from Angular:
1 2 3 4 5 6 7 8 9 |
//add windows authentication for http options request services.AddAuthentication(IISDefaults.AuthenticationScheme); services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); |
Go to the properties window of the Api project, in the Debug tab enable SSL, Anonymous Authentication, and Windows Authentication. You can set the App URL as https.
In the Api project the AccountController returns the Windows account name from HttpContext.User.Identity.Name:
1 2 3 4 5 6 7 8 9 10 11 12 |
[Route("api/[controller]")] [ApiController] public class AccountController : ControllerBase { // GET: api/<AccountController> [HttpGet] public string Get() { IPrincipal p = HttpContext.User; return p.Identity.Name; } } |
Therefore if you go to the url in the browser it will give you the windows account name:
The CustomerController class also uses HttpContext.User.Identity.Name to save the user that added or edited the customer:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
[HttpPut("{id}")] public async Task<ActionResult<Customer>> PutCustomer(int id, Customer customer) { customer.UpdatedBy = HttpContext.User.Identity.Name; return Ok(await this.CustomerData.Update(customer)); } [HttpPost] public async Task<ActionResult<Customer>> PostCustomer(Customer customer) { customer.UpdatedBy = HttpContext.User.Identity.Name; return Ok(await this.CustomerData.Add(customer)); } |
To set up the database, update the database connection string in appsettings.Development.json to point to your Sql Server, then from the command prompt navigate to the Data folder of the API and run the command below, which will create the database and the objects needed in the database:
1 |
dotnet ef database update -s ..\Api\Api.csproj |
Angular Setup
The WinAuthInterceptor class is added to include the Windows Account credential when making Http request to the API:
1 2 3 4 5 6 7 8 9 10 |
@Injectable() export class WinAuthInterceptor implements HttpInterceptor{ constructor(){} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { req = req.clone({ withCredentials: true }); return next.handle(req); } } |
The interceptor is added to app.module.ts:
1 2 3 4 5 6 |
providers: [{ provide: HTTP_INTERCEPTORS, useClass: WinAuthInterceptor, multi: true } ], ... |
The AccountService class is added for getting the windows account name from the API so that it can be shown to the user:
1 2 3 4 5 6 7 8 9 10 |
@Injectable({ providedIn: 'root' }) export class AccountService { ... //get the user's windows account from api get(): Observable<string> { return this.http.get(this.url, {responseType: 'text'}); } } |
The TopBarComponent calls the AccountService for displaying the windows account name.
With the API running in IIS Express and Angular running locally, you should be able to view, add, edit, and delete customers. Once the testing is ok, the next step is to publish the API to an IIS server and have Angular call it for testing.
IIS Setup for API
First make sure to install .Net Core Hosting Bundle for your IIS as it cannot run .Net Core projects without the hosting bundle.
Create the application pool for the API, choose No Managed Code:
The Advanced Settings of the application pool should Disable the 32-bit applications (assuming you are running on x64), and update the Identity to an user account that has Admin privilege on the server:
Now you can create the website in IIS. For the website make sure both Anonymous and Windows Authentication are enabled:
For the Bindings choose https with IIS Express Development Certificate for testing purposes:
Point the website to a directory where you will publish your API project, then you can publish your API project to location. When publish, make sure to choose the correct target runtime. Below example assumes you have the .Net framework installed on the server and therefore choosing Framework-Dependent will be ok.
Now you can go to the url under IIS and see that it will also return the windows account, and pointing your Angular application to it will work as well.
And that’s all. Hope you will find this article useful in adding Windows Authentication to your projects.