Welcome back! In this post, we're going to implement jwt token based security in .Net Core and authenticate APIs with access and refresh token. πŸ‹οΈβ€β™€οΈOf course since this will be an API project, We'll need a front end to call those APIs from. In that case, we'll use Angular 8 or whichever is the latest version of it.

Yes! This is a step by step guide to implement token-based authentication in .Net Core. πŸ˜ŠπŸ‘ and also since it is going to be a one long post, I'm going to have to divide it into multiple posts. Here is the overview of the series.

  1. Create a new .Net Core project, create UserModel and configure entity framework to perform CRUD on Users table. πŸ’»
  2. Configure .Net Core project for jwt authentication. πŸ”
  3. Develop AccountController and create endpoints for authentication. πŸ–‡
  4. Implement authentication APIs to front end. πŸ₯

Create a New .Net Core Project πŸš€

I have created a project and named it PizzaParlor. You can create it using dotnet new PizzaParlor but I preffer using Visual Studio.

Visual Studio 2019 Create ASP.NET Core Web Application
Visual Studio 2019 Create ASP.NET Core Web Application

I have also added entity framework as we'll be using it to perform all kinds of CRUD on Users table.

NuGet Package - Microsoft Entity Framework Core
NuGet Package - Microsoft Entity Framework Core

And here is the User model class.

public class UserModel
{
    public int Id { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string Email { get; set; }
    [Required]
    public string Password { get; set; }
    public string LastRefreshToken { get; set; }
}

Now one last thing that we need is a DbContext class so that Entity Framework can create relevant tables from the exposed dbset(s) and perform CRUD on it. And here it is. πŸ‘‡

public class PPContext: DbContext
{
    public DbSet<UserModel> Users { get; set; }

    public PPContext(DbContextOptions options): base(options) { }

    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.HasDefaultSchema("PizzaParlorMaster");
    }
}

Now modify ConfigureServices method in Startup.cs file as below.

public void ConfigureServices(IServiceCollection services)
{
    ...
    
    // configure ef service
    services.AddDbContext<PPContext>(options => options.UseSqlServer(@"Server=localhost;Database=PizzaParlorMaster;Trusted_Connection=True;"));

    ...
}

Our PizzaParlor is now all set to move forward. 🍾In next post, I'll set it up for JWT authentication.

Stay tuned and I'll see you in next one. πŸ––

Source Files

#nodesignpattern #bareminimumsetup #dotnetcore2 #angular8