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)
该类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)
| 归档时间: |
|
| 查看次数: |
587 次 |
| 最近记录: |