3

I am trying to build a web api in .NET core 3.1 which first tries to get a bearer token through windows authentication and then uses this token to autenticate further requests.

It seems that it is not allowed to use both windows authentication and bearer in a single web api controller. I want to have to controllers for which one uses windows authentication and another uses bearer authentication. This is my controller method:

[HttpGet]
[Route("api/token")]       
[Authorize(AuthenticationSchemes = "Windows")]
public async Task<IActionResult> AuthorizeAsync(CancellationToken cancellationToken) 
{
   // Do something
}

this is for my bearer auth-scheme:

_services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;              
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = !string.IsNullOrWhiteSpace(tokenProviderOptions.SigningKey),
                    IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(tokenProviderOptions.SigningKey)),
                    ValidateIssuer = !string.IsNullOrWhiteSpace(tokenProviderOptions.Issuer),
                    ValidIssuer = tokenProviderOptions.Issuer,
                    ValidateAudience = !string.IsNullOrWhiteSpace(tokenProviderOptions.Audience),
                    ValidAudience = tokenProviderOptions.Audience,
                    RequireExpirationTime = true,
                    ValidateLifetime = !string.IsNullOrWhiteSpace(tokenProviderOptions.TokenLifeTime),
                    ClockSkew = TimeSpan.FromSeconds(0),
                };               
            });

and in my startup I add windows auth:

 services.AddAuthentication("Windows").AddNegotiate();

I have read answers that you cannot call AddAuthentication twice since the second call will override the configuration of the first call, but no solution provided in these question.

So how to mix windows authentication and bearer tokens in one web api controller?

The only possible solution I have found is to override the middleware and for certain paths override the 401 to an unknow response (for example: 418)

I have looked at this question: ASP.Net Core 2.0 mixed authentication of JWT and Windows Authentication doesn't accept credentials

1 Answers1

2

You can add multiple AuthenticationSchemes as it is a comma delimited string property.

[Authorize(AuthenticationSchemes = "Windows,Bearer")]
klekmek
  • 533
  • 3
  • 11