Web API with authorization keeps prompting for sign in

Viewed 205

I am trying to make an ASP.NET Core Web API, which uses Windows AD groups for sign in. Based on the documentation, I have configured the authorization and authentication in the Startup.ConfigureServices() method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthorization(options =>
    {
        options.AddPolicy("Reader", policy => policy.RequireRole(@"<DOMAIN>\<AD_ROLE_NAME>"));
    });

    services
        .AddAuthentication(NegotiateDefaults.AuthenticationScheme)
        .AddNegotiate();

    services.AddControllers();
}

I have then added the [Authorize] attribute to my controller, to ensure than only users who are a member of the AD group, can get access to the end point:

[Authorize(Policy = "Reader")]
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
    var rng = new Random();
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
    })
    .ToArray();
}

If I run the API (from Visual Studio) with IIS, it seems to work fine. However, if I change it the execution method which has the same name as the API (I think it's Kestrel?), then it keeps prompting me for sign in.

How do I get it to work with Kestrel (or whatever that other option is)?

IIS works, Kestrel does not

The sign in box keeps popping up

1 Answers

You need to configure authentication and authorization in the HTTP pipeline through the Configure method:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    .
    .
    app.UseAuthentication(); // You need to setup the authentication before the authorization
    app.UseAuthorization();
    .
    .
}

In ConfigureServices you are already adding the Authentication with .AddAuthentication(NegotiateDefaults.AuthenticationScheme). In this method the order used to register the services doesn't matter because we are just adding the registrations for the DI provider.

In Configure the order is important because we configure the HTTP pipeline, so if a middleware is added before another one, then it is also executed before it.

Authorization works by checking the role of the authenticated user, so we really need to make sure that the authentication process is done before the authorization one.

When your application is hosted under IIS we have IIS caring of the authentication, so this is why it works. In launchSettings.json you have probably something like:

{
    .
    .
    "iisSettings": {
        "windowsAuthentication": true,
        "anonymousAuthentication": false,
        .
        .
    }
    .
    .
}

That configure the IIS authentication module

Related