Home > Enterprise >  ASP.NET core how to use Authentication only for specific routes?
ASP.NET core how to use Authentication only for specific routes?

Time:07-30

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.

CodePudding user response:

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.

  • Related