0

In a aspnet.core application I added the following middleware:

app.Use(async (context, next) =>
{
    var authService = context.RequestServices.GetRequiredService<IAuthenticationService>();

    AuthenticateResult result = null;

    // Try JWT first
    if (context.Request.Headers.ContainsKey("Authorization"))
    {
        result = await authService.AuthenticateAsync(context, JwtBearerDefaults.AuthenticationScheme);
    }

    // If JWT fails or wasn't present, try Windows
    if (result == null || !result.Succeeded)
    {
        result = await authService.AuthenticateAsync(context, NegotiateDefaults.AuthenticationScheme);
    }

    if (result?.Succeeded == true)
    {
        context.User = result.Principal!;
    }

    await next();
});

I setup the Authentication Services like this:

services.AddAuthentication( options =>
{
    options.DefaultAuthenticateScheme = NegotiateDefaults.AuthenticationScheme;
})
.AddNegotiate()
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = Configuration.GetValue<string>("TokenValidIssuer"),
        ValidAudience = Configuration.GetValue<string>("TokenValidAudience"),
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetValue<string>("SuperSecretKey")))
    };
});

The app is hosted in IIS. The problem is that when I allow Anonymous Authentication in IIS together with the Windows one, the Windows Authentication in the middleware stops to work, the result is not authenticated. Can someone help me how to set the IIS?

3
  • In Configure(...) pipeline, order matters: routing → authentication → authorization → endpoints: Commented Jun 25 at 8:58
  • This has been well known. The meaning of anonymous authentication is that it should take highest priority and stop other authentication methods from working. Commented Jun 25 at 16:18
  • Try enabling forwardWindowsAuthToken in your web.config. Commented Jun 26 at 1:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.