Search code examples
asp.net-coredependency-injectionauthorizationentity-framework-coreasp.net-core-identity

Access EF DbContext within Google OAuth flow


I have a working Google authentication flow in ASP.NET Core 2.1.

I would like to add some authorization by checking the user's email address against a database when they sign in. How can I access the Entity Framework DbContext here?

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();
  /* ... */
}

Solution

  • You can access your HttpContext from context and you can access the IServiceProvider from there.

     context.HttpContext.RequestServices.GetService<Database>()