ASP.NET Core - Angular application with Windows auth

 

Visual Studio 2022 does not provide an option to scaffold an Angular application with Windows authentication. In this blog post I document the required steps to get Windows authentication working for Angular and .NET 7.

You can start with the default template in Visual Studio. Select "None" as "Authentication type" Scaffold Angular.png

In ClientApp/proxy.conf.js you'll have to use the following setup (you may have to adjust the port 55781 in line 5)

const { env } = require('process');
const HttpsAgent = require('agentkeepalive').HttpsAgent;

const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
  env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'http://localhost:55781';

const PROXY_CONFIG = [
  {
    context: ["/api"],
    target: target,
    secure: false,
    changeOrigin: true,
    agent: new HttpsAgent({
      maxSockets: 100,
      keepAlive: true,
      maxFreeSockets: 10,
      keepAliveMsecs: 100000,
      timeout: 6000000,
      freeSocketTimeout: 90000
    }),
    onProxyRes: proxyRes => {
      const key = "www-authenticate";
      proxyRes.headers[key] = proxyRes.headers[key] &&
        proxyRes.headers[key].split(",");
    }
  }
]

module.exports = PROXY_CONFIG;

In Program.cs you'll have to add authentication und authorization:

builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy.
    options.FallbackPolicy = options.DefaultPolicy;
});
app.UseAuthentication();
app.UseAuthorization();

Now you can start to use [Authorize] attributes in your controllers/actions.

Source Code

The complete source code can be found on GitHub.

Feedly Feedly Tweet


Related posts


Comments


Vinayak

Vinayak

12/15/2023

Will this will work when I want to get the user id who is currently open the web application , We need to get window authentication to work.


Aaron Nay

Aaron Nay

9/12/2023

This article was critically helpful to my team and our project. Thank you!


Daniel

Daniel

5/11/2023

@Steven: Windows auth does not work in Docker out of the box. You need to setup a reverse proxy like NGINX. See here: https://stackoverflow.com/questions/68640236/asp-net-core-windows-authentication-with-docker


Steven

Steven

5/11/2023

Great Article! I've been trying for quite a while to get this exact combination (angular + asp.net core + windows auth) to work. Running on windows it worked straight away. The only thing is that I would like to host the app in a docker linux container and the authentication doesn't seem to work under linux. Does this generally not work or is there a (hopefully simple) solution to this problem?