我在ASP中有一个工作的Google身份验证流。NET Core 2.1。
我想通过在用户登录时对照数据库检查用户的电子邮件地址来添加一些授权。如何访问实体框架 DbContext 在这里
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 从那里开始。
HttpContext
IServiceProvider
context.HttpContext.RequestServices.GetService<Database>()