c# - 用户首次使用 OpenId Connect 登录后,将新 UserId 放入数据库的位置在哪里?

标签 c# asp.net-core openid-connect asp.net-core-2.1

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

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;
}

最佳答案

UserInformationReceivedContext 类包括 HttpContext 属性,它本身包含一个 RequestServices 属性(property)。这RequestServices属性类型为 IServiceProvider ,可用于访问依赖注入(inject)容器中注册的服务。

这是一个使用 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;
}

关于c# - 用户首次使用 OpenId Connect 登录后,将新 UserId 放入数据库的位置在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51493446/

相关文章:

c# - asp.net core登录功能错误 "not all code paths return a value"

asp.net-core - 如何在 ASP.NET Core API 中的 Swagger 中将注释显示为描述段落

java - 如何克服 thymeleaf 模板批准错误?

c# - 身份服务器 4 OpenId Connect 重定向到/Account/AccessDenied

c# - 从这些 foreach 循环中的一个列表中删除如何从另一个列表中删除?

c# - 如何卸载已加载的程序集

azure - 部署到 Azure 后收到 404

c# - 验证字符串 - 仅特定语言字符

c# - 使用代码验证 Microsoft Dynamics CRM

javascript - 只有当我使用 IE11 时,事件 addUserSignedOut 才会自动触发