简体   繁体   中英

Use both windows authentication and bearer tokens in one web api

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. 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?

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

[Authorize(AuthenticationSchemes = "Windows,Bearer")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM