asp.net-core - ASP.NET Core 使用自定义配置文件丰富 IIdentity
问题描述
我正在使用 Azure AD 对用户进行授权和身份验证。所有用户在数据库中都有一个配置文件。
我想在登录时始终将 Azure 用户与我的数据库用户“合并”。
这是我用来在我的 web api 中设置身份验证的代码。
public static partial class ServiceCollectionExtensions
{
public static IServiceCollection AddBearerAuthentication(this IServiceCollection services,
OpenIdConnectOptions openIdConnectOptions)
{
#if DEBUG
IdentityModelEventSource.ShowPII = true;
#endif
services
.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", o =>
{
o.Authority = openIdConnectOptions.Authority;
o.TokenValidationParameters.ValidIssuer = openIdConnectOptions.ValidIssuer;
o.TokenValidationParameters.ValidAudiences = openIdConnectOptions.ValidAudiences;
});
return services;
}
}
有人可以指出我正确的方向吗?现在我在我所有的控制器中加载用户,一点也不漂亮。
解决方案
不确定“合并”用户是什么意思。但是,如果您只想为每个传入的 http 请求运行一些逻辑,您可以添加一个自定义中间件
app.Use(async (context, next) =>
{
var user = await context.RequestServices
.GetRequiredService<DatabaseContext>()
.Users
.Where(....)
.SingleOrDefaultAsync();
...
await next(context);
});
或者,如果您非常想将代码与身份验证过程结合起来,您可以使用来自的回调JwtBearerOptions
.AddJwtBearer("Bearer", o =>
{
...
o.Events.OnTokenValidated = async context =>
{
var user = await context.HttpContext
.RequestServices
.GetRequiredService....
...
};
}
但就个人而言,我认为这两种方法都不好。每次请求都去数据库获取用户的凭据对性能不利。此外,它有点违背 JWT 的全部观点,JWT 专门设计用于不这样做。令牌应该已经包含里面的所有声明。如果没有,我建议重新配置 azure AD,或切换到自发行令牌。
推荐阅读
- android - Android - 致命崩溃'信号 11 (SIGSEGV),代码 1 (SEGV_MAPERR) strcmp'
- ipad - ARFrame.camera.capturedImage 的分辨率与真实相机分辨率或显示分辨率不同
- python - 未找到 Python selenium webdriver 元素
- docker - 访问docker容器映射的端口 :curl: (56) Recv failure: Connection reset by peer
- r - R Shiny Apps Io w/ Access 数据库
- javascript - Javascript/JSON 根据属性内的最高键值拉取键值
- sql - 根据输入在Column上添加变量并显示实际值
- unity3d - 除操纵杆区域外检测触摸的有效方法
- css - TeXworks - 我无法更改字体颜色
- android - 如何在外壳中使用(android)R8?