Search code examples
c#asp.netasp.net-corejwtasp.net-core-2.1

Is it necessary to create tables like AspNetUsers while adding JWT authentication to ASP.NET Core 2.1 Web API?


I am trying to create a simple ASP.NET Core 2.1 Web API to serve data from an SQL Server database. I want to use JWT-based bearer authentication for access to the API via simple username and password credentials, nothing too complex. So far, I have been able to create a simple Core 2.1 Web API project with non-authenticated CRUD operations enabled, but adding JWT support to it is proving to be a little problematic.

My database has a table called Users which houses personal information of the users, which includes username and password hash fields. I want to use this same table for JWT based authentication. However, most of the tutorials on the topic (like this) use the concept of migration which adds several tables (e.g. AspNetUserTokens and AspNetUserLogins) to my database, which seems pretty useless to me as I do not plan on using external authentication like Google or Facebook. Even the table AspNetUsers contains seemingly redundant fields.

I also tried following this tutorial with in-memory datastore but couldn't implement SQL Server integration to it (facing a lot of errors like Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager' and Cannot create a DbSet for 'IdentityUser' this type is not included in the model for the context).

Can I add JWT-based authentication to an ASP.NET Core 2.1 Web API with SQL Server database integration without the migration procedure (especially in the context of this project)?


Solution

  • Can I add JWT-based authentication to an ASP.NET Core 2.1 Web API with SQL Server database integration without the migration procedure (especially in the context of this project)?

    Yes, you can. You don't need to use IdentityServer (and it's migration process) just because you're handling user data. You can perfectly fine create your own implementation of the user handling as the one in this link


    To add the SQL Server integration, look at the StartUp.cs class in the linked project, this line

    services.AddDbContext<DataContext>(x => x.UseInMemoryDatabase("TestDb"));
    

    Change that line and point out your database connectionstring

    services.AddDbContext<DataContext>(x => x.UseSqlServer("yourConnectionstring"));