簡體   English   中英

在一個 web api 中同時使用 windows 身份驗證和不記名令牌

[英]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.

似乎不允許在單個 web api 中同時使用 windows 身份驗證和承載。 我想擁有一個使用 windows 身份驗證和另一個使用承載身份驗證的控制器。 這是我的 controller 方法:

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

這是我的不記名身份驗證方案:

_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),
                };               
            });

在我的啟動中,我添加了 windows 身份驗證:

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

我已經閱讀了您不能兩次調用AddAuthentication的答案,因為第二次調用將覆蓋第一次調用的配置,但這些問題中沒有提供解決方案。

那么如何在一個 web api 中混合 windows 身份驗證和不記名令牌?

您可以添加多個 AuthenticationSchemes,因為它是一個逗號分隔的字符串屬性。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM