【问题标题】:ASP.NET Core enrich IIdentity with custom profileASP.NET Core 使用自定义配置文件丰富 IIdentity
【发布时间】:2021-07-09 05:58:00
【问题描述】:

我正在使用 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-core identity iprincipal


    【解决方案1】:

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

    【讨论】:

    • 首先感谢您的回答。我们有很多应用程序都有一些关于用户的数据,称之为偏好。当您在 Asp.Net 核心 web api 中使用控制器时,我想将该数据与线程上的用户“合并”
    • 您不能合并用户身份,它们是只读的,但您可以添加一个新的context.User.AddIdentity(...)
    • 我知道。我需要创建一个自定义身份。我需要改写我的问题,因为我知道你不能合并它,所以我把它放在引号里。我只需要帮助扩展我在 Azure AD 身份验证后拥有的对象
    猜你喜欢
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多