【问题标题】:How to support multiple authentication scheme in Web API Core 2?如何在 Web API Core 2 中支持多种身份验证方案?
【发布时间】:2018-03-07 09:43:09
【问题描述】:

我正在开发一个 web api core 2.0 项目。

我需要支持两种授权类型:jwt 和 basic。

在我的 ConfigureServices 方法中,我添加了以下代码:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer((options) =>
{
    options.Authority = $"...";
    options.Audience = "...";
});

services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
.AddBasicAuthentication(credentials =>
Task.FromResult(
   credentials.username == "username"
   && credentials.password == "password"));

在我的 Configure 方法中,我添加了以下代码:

app.UseAuthentication();
app.UseMvc();

最后我在我的控制器上添加了 AuthorizeAttribute

[Authorize]
public class MioController : Controller
{ ... }

实际上只使用 ConfigureServices 上指定的最后一次身份验证。

如何支持这两种身份验证类型? 谢谢

注意:我正在使用这个 NuGet 包进行基本身份验证Bazinga.AspNetCore.Authentication.Basic

【问题讨论】:

  • Authorize 属性具有相关属性:[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

标签: c# authentication asp.net-core


【解决方案1】:

尝试在一个链中添加您的身份验证服务

services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer((options) =>
{
    options.Authority = $"...";
    options.Audience = "...";
})
.AddBasicAuthentication(credentials =>
{
    Task.FromResult(credentials.username == "username" && credentials.password == "password"));
}

也可以在AuthorizeAttribute 上指定要使用哪个方案对请求进行身份验证

[Authorize(AuthenticationSchemes = BasicAuthenticationDefaults.AuthenticationScheme + ", " + JwtBearerDefaults.AuthenticationScheme)]

【讨论】:

  • 嗨,Kahbazi,我已经实施了你的建议,但现在只使用不记名 (jwt) 的授权。
  • 您需要使用[Authorize(AuthenticationSchemes = BasicAuthenticationDefaults.AuthenticationScheme)]进行basicAuthentication进行身份验证。默认情况下,只有 JWT 会对每个请求进行身份验证
  • 嗨 Kahbazi,使用 BasicAuthenticationScheme 我遇到了同样的问题,但使用了基本身份验证。
  • 我已经解决了 [Authorize(AuthenticationSchemes = BasicAuthenticationDefaults.AuthenticationScheme + ", " + JwtBearerDefaults.AuthenticationScheme)]
猜你喜欢
  • 2022-07-27
  • 2021-08-27
  • 2021-10-18
  • 2019-08-31
  • 2018-02-23
  • 2014-03-25
  • 1970-01-01
  • 2022-01-04
  • 2018-03-23
相关资源
最近更新 更多