如何在Web API Core 2中支持多种身份验证方案? [英] How to support multiple authentication scheme in Web API Core 2?

查看:81
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆