如何在Web API Core 2中支持多种身份验证方案? [英] How to support multiple authentication scheme in Web API Core 2?
问题描述
我正在开发一个Web api core 2.0项目.
I'm developing a web api core 2.0 project.
我需要支持两种授权类型:jwt和basic.
I need support two authorization types: jwt and basic.
在我的 ConfigureServices 方法中,我添加了以下代码:
Inside my ConfigureServices method I've added this code:
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 方法中,我添加了以下代码:
Inside my Configure method I've added this code:
app.UseAuthentication();
app.UseMvc();
最后,我在控制器上添加了 AuthorizeAttribute :
And finally I've added AuthorizeAttribute on my controller:
[Authorize]
public class MioController : Controller
{ ... }
实际上只工作在 ConfigureServices 中指定的最后一次身份验证.
Actually work only the last authentication specified on ConfigureServices.
我如何支持两种身份验证类型? 谢谢
How can I support both authentication types? Thanks
注意:我正在使用此NuGet软件包进行基本身份验证 Bazinga .AspNetCore.Authentication.Basic .
推荐答案
尝试将您的身份验证服务添加到一个链中
try Adding your authentication service in one chain
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer((options) =>
{
options.Authority = $"...";
options.Audience = "...";
})
.AddBasicAuthentication(credentials =>
{
Task.FromResult(credentials.username == "username" && credentials.password == "password"));
}
,也可以在AuthorizeAttribute
上指定要使用哪个方案来认证请求的方式
and also on AuthorizeAttribute
you can specify which Scheme you want to authenticate the request with
[Authorize(AuthenticationSchemes = BasicAuthenticationDefaults.AuthenticationScheme + ", " + JwtBearerDefaults.AuthenticationScheme)]
这篇关于如何在Web API Core 2中支持多种身份验证方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!