在 Google OAuth 流程中访问 EF DbContext
Access EF DbContext within Google OAuth flow
我在 ASP.NET Core 2.1 中有一个可用的 Google 身份验证流程。
我想通过在用户登录时根据数据库检查用户的电子邮件地址来添加一些授权。如何在此处访问 Entity Framework DbContext
?
public void ConfigureServices(IServiceCollection services)
{
services
.AddDbContext<Database>(options => options.UseSqlServer(Configuration["SqlServer"]));
services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o =>
{
o.LoginPath = "/Auth/SignIn";
o.LogoutPath = "/Auth/SignOut";
o.ExpireTimeSpan = TimeSpan.FromDays(90);
})
.AddGoogle(o =>
{
o.ClientId = Configuration["Auth:Google:ClientId"];
o.ClientSecret = Configuration["Auth:Google:ClientSecret"];
o.Events = new OAuthEvents()
{
OnTicketReceived = async context =>
{
var email = context.Principal.Identity.GetEmail().ToLowerInvariant();
if (/* User not in database */) // <-- How can I access the EF DbContext here?
{
context.Response.Redirect("/Auth/Unauthorised");
context.HandleResponse();
}
}
};
});
services.AddMvc();
/* ... */
}
您可以从上下文访问您的 HttpContext
,也可以从那里访问 IServiceProvider
。
context.HttpContext.RequestServices.GetService<Database>()
我在 ASP.NET Core 2.1 中有一个可用的 Google 身份验证流程。
我想通过在用户登录时根据数据库检查用户的电子邮件地址来添加一些授权。如何在此处访问 Entity Framework DbContext
?
public void ConfigureServices(IServiceCollection services)
{
services
.AddDbContext<Database>(options => options.UseSqlServer(Configuration["SqlServer"]));
services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o =>
{
o.LoginPath = "/Auth/SignIn";
o.LogoutPath = "/Auth/SignOut";
o.ExpireTimeSpan = TimeSpan.FromDays(90);
})
.AddGoogle(o =>
{
o.ClientId = Configuration["Auth:Google:ClientId"];
o.ClientSecret = Configuration["Auth:Google:ClientSecret"];
o.Events = new OAuthEvents()
{
OnTicketReceived = async context =>
{
var email = context.Principal.Identity.GetEmail().ToLowerInvariant();
if (/* User not in database */) // <-- How can I access the EF DbContext here?
{
context.Response.Redirect("/Auth/Unauthorised");
context.HandleResponse();
}
}
};
});
services.AddMvc();
/* ... */
}
您可以从上下文访问您的 HttpContext
,也可以从那里访问 IServiceProvider
。
context.HttpContext.RequestServices.GetService<Database>()