Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 https://stormpath.com/blog/token-authentication-asp-net-core.

All was going well until I had to replace the hard-coded username and passwords in the GetIdentity 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. https://github.com/nbarbettini/SimpleTokenProvider/blob/master/test/SimpleTokenProvider.Test/Startup.Auth.cs

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?
like image 234
Top Rat Avatar asked Aug 02 '16 19:08

Top Rat


People also ask

What is the role of startup class in .NET Core?

ASP.NET Core apps use a Startup class, which is named Startup by convention. The Startup class: Optionally includes a ConfigureServices method to configure the app's services. A service is a reusable component that provides app functionality.

How do you inject dependency in startup CS?

The implementation class of above interface having dummy data. Then we have to create a Controller(API) for calling this repo, and inject this interface into this. In the last, we have to register it in Startup class. Also mention which type of instance want to inject - (the lifetime) of our instance.

What is Startup Cs in ASP.NET Core?

The Startup class in .NET and .NET CoreThe Startup class contains the ConfigureServices and Configure methods. While the former is used to configure the required services, the latter is used to configure the request processing pipeline. The Configure method is executed immediately after the ConfigureServices method.


2 Answers

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. :)

like image 63
Nate Barbettini Avatar answered Oct 24 '22 08:10

Nate Barbettini


On .NET CORE 2.1, just pass the context as an argument to the Configure method:

public void Configure(IApplicationBuilder app, YourDbContext context, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
        //do whatever you want with the context here...
}

Adding services to the service container makes them available within the app and in the Configure method. The services are resolved via dependency injection or from ApplicationServices.

like image 16
juanora Avatar answered Oct 24 '22 09:10

juanora