新用户首次通过本地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/