asp.net-core - 在 Google OAuth 流程中访问 EF DbContext

标签 asp.net-core dependency-injection authorization entity-framework-core asp.net-core-identity

我在 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 - 在 Google OAuth 流程中访问 EF DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49676795/

相关文章:

javascript - 如何在针对 JavaScript 的 Kotlin 中使用依赖注入(inject)?

c# - 在 asp.net core 中需要经过身份验证的用户,但在某些操作中需要自定义策略需要自定义策略

authentication - 如何使用 JWT token 管理多设备同时登录?

debugging - VS 2015 Update 2 - 调试时变量不存在,为什么?

java - Spring Beans 中的构造函数参数太多

json - 如何通过来自 Asp.Net Core 中间件的 JsonResult 做出响应?

asp.net-core - IOptions<T> 的简化方法

oauth - 在微服务之间传递用户身份和授权

asp.net-core - 如何从 MVC Controller 使用 Azure Function

asp.net-core - .NET 6 向后兼容使用 .NET Core 3.1 目标框架开发的应用程序