首页 > 解决方案 > 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;
    }
}

有人可以指出我正确的方向吗?现在我在我所有的控制器中加载用户,一点也不漂亮。

标签: asp.net-coreidentityiprincipal

解决方案


不确定“合并”用户是什么意思。但是,如果您只想为每个传入的 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,或切换到自发行令牌。


推荐阅读