用户首次使用 OpenId Connect 登录后,将新的 UserId 放入 DB 的位置在哪里?

Ars*_*ync 5 c# openid-connect asp.net-core asp.net-core-2.1

本地IdentityServer4通过OpenIdConnect首次访问站点时需要注册一个新用户。找到了在事件中执行此操作的“最佳位置” OnUserInformationReceived,但不确定如何在事件处理程序(启动类)中访问 EF DbContext。没有 DI 用于获取 DbContext 的预配置实例(它在其构造函数中请求其他依赖项)。

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie("Cookies")
        .AddOpenIdConnect("oidc", options =>
        {
            options.SignInScheme = "Cookies";

            // ...

            options.Events.OnUserInformationReceived = OnUserInformationReceived;
        });

    // ...
}

private Task OnUserInformationReceived(UserInformationReceivedContext c)
{
    var userId = c.User.Value<string>(JwtRegisteredClaimNames.Sub);

    // Call DbContext to insert User entry if doesn't exist.
    // Or there is another place to do that?

    return Task.CompletedTask;
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*kin 5

该类UserInformationReceivedContext包含一个HttpContext属性,该类本身也包含一个RequestServices属性。该RequestServices属性的类型为IServiceProvider,可用于访问依赖注入容器中注册的服务。

这是一个使用的示例GetService<T>

private Task OnUserInformationReceived(UserInformationReceivedContext c)
{
    var userId = c.User.Value<string>("sub");    
    var dbContext = c.HttpContext.RequestServices.GetService<YourDbContext>();

    // Use dbContext here.

    return Task.CompletedTask;
}
Run Code Online (Sandbox Code Playgroud)