将 Azure-AD 与 dotnet core 2 web-api 中的本地用户数据库相结合 [英] Combine Azure-AD with local user database in dotnet core 2 web-api
问题描述
我正在创建一个 .net-core2 web-api,它允许来自 Azure-AD 的用户使用它.API 是多租户的,因此来自多个 Azure-AD 的用户应该能够进行授权.
I am creating a .net-core2 web-api, which allows users from an Azure-AD to consume it. The API is multi-tenant, so users from multiple Azure-AD's should be able to authorize.
但是,也可以为没有公司 Azure-AD 帐户的用户创建帐户.这些用户存储在数据库中(本地用户).
However, it is also possible to create an account for users who do not have a corporate Azure-AD account. These users are stored in a database (local users).
因为是web-api,所以我实现了自定义token provider,这样本地用户就可以拿到token来消费受保护的web-api.
Because it is a web-api, I implemented a custom token provider, so that the local users can get a token to consume the protected web-api.
但是,我无法向 web-api 添加两个单独的承载"身份验证:
However, I cannot add two separate 'Bearer' authentications to the web-api:
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddAzureAdBearer(options => Configuration.Bind("AzureAd", options))
.AddJwtBearer(options => new JwtBearerOptions {
TokenValidationParameters = tokenValidationParameters
});
这会引发错误:
System.InvalidOperationException:Scheme 已经存在:Bearer
System.InvalidOperationException: Scheme already exists: Bearer
我完全理解.但是我如何并行实现两种身份验证机制?
Which I totally understand. But how I can implement both authentication mechanisms in parallel?
推荐答案
您必须指定不同的标识符.两者目前都在使用承载"标识符.
You have to specify a different identifier. Both are using the "Bearer" identifier at the moment.
例如,您可以通过以下方式为 JWT Bearer 指定一个不同的:
For example, you can specify a different one for JWT Bearer by:
.AddJwtBearer("CustomJwt", options => { });
这解决了标识符冲突的问题,但为了同时支持两种身份验证方案,您需要进行额外的修改.
This solves the issue with the identifier clash, but in order to support two authentication schemes in parallel, you will need to do additional modifications.
David Fowler 建议了 2.0 中的一种方法:https://github.com/aspnet/Security/issues/1469
One way in 2.0 is something suggested by David Fowler: https://github.com/aspnet/Security/issues/1469
app.UseAuthentication();
app.Use(async (context, next) =>
{
// Write some code that determines the scheme based on the incoming request
var scheme = GetSchemeForRequest(context);
var result = await context.AuthenticateAsync(scheme);
if (result.Succeeded)
{
context.User = result.Principal;
}
await next();
});
在您的情况下,如果您点击中间件时上下文中没有用户,您可以使用所有承载 (Azure AD) 方案.
In your case you could all the Bearer (Azure AD) scheme if there is no user on the context when you hit the middleware.
在 ASP.NET Core 2.1 中,我们将获得虚拟身份验证方案",它以更一流的方式允许这种情况:https://github.com/aspnet/Security/pull/1550
In ASP.NET Core 2.1 we will get "virtual authentication schemes", which allow this scenario in a more first-class way: https://github.com/aspnet/Security/pull/1550
这篇关于将 Azure-AD 与 dotnet core 2 web-api 中的本地用户数据库相结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!