Top Rat Top Rat - 1 month ago 15x
C# Question

Can I access a database during startup in ASP.NET Core?

I have recently been working on a .NET Core web API. I have just attempted authentication using JWT, by following the guide on

All was going well until I had to replace the hard-coded username and passwords in the

method with a DB query and realized I do not know how to access the DB from within this file!

The method I am referring to is shown in the link below on line 70.

My questions are as follows.

  1. Can I access the database here? If so how?

  2. Should this be where the GetIdentity method is, or is there a better way?


Yes, you can access the database! Code that runs in the Configure method can access any services that are added in the ConfigureServices method, including things like database contexts.

For example, if you have a simple Entity Framework context:

using Microsoft.EntityFrameworkCore;
using SimpleTokenProvider.Test.Models;

namespace SimpleTokenProvider.Test
    public class SimpleContext : DbContext
        public SimpleContext(DbContextOptions<SimpleContext> options)
            : base(options)

        public DbSet<User> Users { get; set; }

And you add it in ConfigureServices:

services.AddDbContext<SimpleContext>(opt => opt.UseInMemoryDatabase());

Then, you can access it when you are setting up the middleware:

var context = app.ApplicationServices.GetService<SimpleContext>();

app.UseSimpleTokenProvider(new TokenProviderOptions
    Path = "/api/token",
    Audience = "ExampleAudience",
    Issuer = "ExampleIssuer",
    SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
    IdentityResolver = (username, password) => GetIdentity(context, username, password)

And rewrite the GetIdentity method a little:

private Task<ClaimsIdentity> GetIdentity(SimpleContext context, string username, string password)
    // Access the database using the context
    // Here you'd need to do things like hash the password
    // and do a lookup to see if the user + password hash exists

I'm the author of the original sample. Sorry it wasn't clear initially! I tried to write the IdentityResolver delegate in a way that makes it easy to provide your own functionality -- like integrating with your own database (as above), or hooking it up to ASP.NET Core Identity. Of course, you're free to throw away my code and do something better, too. :)