1

I configured to use windows authentication for my asp.net react app.

on ConfigureServices() method:

services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
services.AddAuthorization(options =>
{
    options.FallbackPolicy = options.DefaultPolicy;
});

then on configure() method:

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

However, by doing so, all requests will trigger the authentication process. I actually only want my api routes (in /api/my/resource ) to be secure using windows authentication, and want to let the whole react resource folder to be public (in /any/path/here).

How do I configure to use windows authentication only for route starting with /api.

KaraNoKara
  • 85
  • 10
  • Hi. Have you tried Authorize & AllowAnonymous attributes https://learn.microsoft.com/en-us/aspnet/core/security/authorization/simple?view=aspnetcore-3.1 – Vidiya Prasanth Pappannan Jul 25 '22 at 22:36
  • 1
    You can implement Role-Based Authorization Or Policy-Based Authorization with Windows Authentication, then in the API controller, use the Authorize attribute to apply the policy to the controller. Refer to the following links: [ASP.NET Core - Authorization Using Windows Authentication](https://stackoverflow.com/questions/53524466/) and [Create Role-Based Authorization with Windows Authentication](https://stackoverflow.com/questions/60105635/). – Zhi Lv Jul 26 '22 at 03:41
  • Thanks, guys. I came up with a way to do it, it is very simple actually. Please see my answer. @ZhiLv – KaraNoKara Jul 26 '22 at 18:53
  • https://stackoverflow.com/a/66776177/214977 – granadaCoder Jul 26 '22 at 20:48

1 Answers1

5

I achieved that by just doing this:

services.AddAuthorization(options =>
{
    // don't use default policy
    // options.FallbackPolicy = options.DefaultPolicy;
});

Then add [Authorize] to the controllers that need authentication.

[Authorize]     // trigger authentication process
[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase {}

Then I can choose specific routes to require authentication.

Connor Low
  • 5,900
  • 3
  • 31
  • 52
KaraNoKara
  • 85
  • 10